691 lines
38 KiB
JavaScript
691 lines
38 KiB
JavaScript
"use strict";
|
|
|
|
// Tests for the dashboard assistant billable-quota rate limits (finding M1a).
|
|
//
|
|
// The assistant endpoints that spend billable provider quota against the
|
|
// panel's stored Groq/Google keys had NO dedicated limiting:
|
|
// - POST /chat fans every user turn out to 1..N billable LLM calls (the
|
|
// tool loop repeats per turn),
|
|
// - POST /client-follow-up spends one billable call (unless skipAi),
|
|
// - POST /transcribe buffers up to 15MB of audio into memory and fires an
|
|
// outbound STT call,
|
|
// - GET /models triggers outbound provider model-list calls on a cold cache.
|
|
// The global /api limiter is no help while the operator-optional
|
|
// security.rate_limiting toggle is off, so these limiters are ALWAYS-ON abuse
|
|
// brakes that never consult security.rate_limiting (same house pattern as the
|
|
// login/recovery/captcha/step-up limiters), keyed per account+session without
|
|
// IP: the threat is a hijacked session or a runaway client, and IP keying
|
|
// would let a network-hopping attacker reset the counters (and burn NAT
|
|
// neighbors' budgets).
|
|
//
|
|
// index.js boots servers on require, so the limiter definitions and wiring
|
|
// are locked with source assertions (same technique as
|
|
// dashboard-assistant-delete-gate.test.js); the router itself is booted with
|
|
// contract-compatible mocks to pin the mounting SEMANTICS: every route mounts
|
|
// its injected limiter, the /transcribe limiter runs BEFORE the auth gate
|
|
// (and therefore before multer buffers any upload bytes), and the router
|
|
// still constructs and serves when deps omit the new limiters (the
|
|
// typeof-fallback keeps existing minimal-deps constructions working).
|
|
//
|
|
// POST /token and POST /access (the assistant config-write endpoints) get the
|
|
// same always-on treatment: /token re-encrypts the provider key and rewrites
|
|
// the shared .env via writeEnvFileBatch (invalidating the decrypted-key cache
|
|
// in every pm2 cluster worker), /access atomically rewrites
|
|
// data/dashboard-assistant-config.json, and their only backstop used to be
|
|
// the operator-optional global limiter that self-disables when
|
|
// security.rate_limiting !== true. Their limiters follow the webhook
|
|
// config-write brake's composite account+session shape, sized below the
|
|
// webhook baseline (20/60 vs 40/120 per 5 min) for the rarer admin action mix.
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
const express = require("express");
|
|
|
|
const createDashboardAssistantRouter = require("../routes/dashboard-assistant.js");
|
|
|
|
const ROOT = path.join(__dirname, "..");
|
|
const INDEX_JS = path.join(ROOT, "index.js");
|
|
const ROUTER_JS = path.join(ROOT, "routes", "dashboard-assistant.js");
|
|
|
|
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
|
const routerSource = fs.readFileSync(ROUTER_JS, "utf8");
|
|
|
|
function assertContains(haystack, needle, label) {
|
|
assert.ok(haystack.includes(needle), `expected to find: ${label || needle}`);
|
|
}
|
|
|
|
// Slice from startMarker up to (excluding) endMarker.
|
|
function extractSlice(source, startMarker, endMarker) {
|
|
const start = source.indexOf(startMarker);
|
|
assert.ok(start >= 0, `marker not found: ${startMarker}`);
|
|
const end = endMarker ? source.indexOf(endMarker, start) : source.length;
|
|
assert.ok(end > start, `end marker not found after ${startMarker}: ${endMarker}`);
|
|
return source.slice(start, end);
|
|
}
|
|
|
|
// Slice a `{ ... }`-balanced block starting at startMarker (for const x =
|
|
// rateLimit({...}) and function-wrapper declarations).
|
|
function extractBlock(source, startMarker) {
|
|
const start = source.indexOf(startMarker);
|
|
assert.ok(start >= 0, `marker not found: ${startMarker}`);
|
|
const bodyStart = source.indexOf("{", start);
|
|
let depth = 0;
|
|
let i = bodyStart;
|
|
for (; i < source.length; i += 1) {
|
|
if (source[i] === "{") depth += 1;
|
|
else if (source[i] === "}") {
|
|
depth -= 1;
|
|
if (depth === 0) {
|
|
i += 1;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
assert.ok(depth === 0, `unbalanced braces after: ${startMarker}`);
|
|
return source.slice(start, i);
|
|
}
|
|
|
|
// The exact key template returned by a limiter block's keyGenerator — the
|
|
// load-bearing "keyed per what" statement.
|
|
function extractKeyTemplate(limiterBlock) {
|
|
const match = limiterBlock.match(/return `([^`]+)`;/);
|
|
assert.ok(match, "keyGenerator returns a template-literal key");
|
|
return match[1];
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// index.js: the always-on limiter definitions
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("index.js defines all three quota limiters as always-on (no security.rate_limiting)", () => {
|
|
// The rationale comment above the definitions explains WHY they are
|
|
// always-on: they guard billable outbound provider calls against the
|
|
// panel's stored keys, so they must not depend on the operator-optional
|
|
// global toggle.
|
|
const comment = extractSlice(
|
|
indexSource,
|
|
"// Dashboard assistant endpoints that spend billable provider quota",
|
|
"const dashboardAssistantCompletionSessionRateLimiter = rateLimit("
|
|
);
|
|
assert.ok(/ALWAYS-ON/.test(comment), "comment marks the limiters as always-on");
|
|
assert.ok(/security\.rate_limiting/.test(comment), "comment names the global toggle they ignore");
|
|
assert.ok(/without IP/.test(comment), "comment explains the email+session keying");
|
|
|
|
const definitions = [
|
|
"const dashboardAssistantCompletionSessionRateLimiter = rateLimit(",
|
|
"const dashboardAssistantCompletionAccountRateLimiter = rateLimit(",
|
|
"const dashboardAssistantTranscribeSessionRateLimiter = rateLimit(",
|
|
"const dashboardAssistantTranscribeAccountRateLimiter = rateLimit(",
|
|
"const dashboardAssistantModelsRateLimiter = rateLimit(",
|
|
];
|
|
for (const marker of definitions) {
|
|
const block = extractBlock(indexSource, marker);
|
|
assert.ok(!block.includes("rate_limiting"), `${marker} must not consult security.rate_limiting`);
|
|
assertContains(block, "standardHeaders: true", "RateLimit standard headers");
|
|
assertContains(block, "legacyHeaders: false", "no legacy headers");
|
|
assertContains(block, "skip: (req) => !req.session?.user", "skips anonymous requests (route auth gates reject those)");
|
|
// The account-wide backstops key on the email alone: if it were not
|
|
// canonicalized, "Admin@x" and "admin@x" would get separate budgets and
|
|
// the per-account cap would silently multiply. Pin the normalization.
|
|
assertContains(
|
|
block,
|
|
'String(req.session?.user || "anon").trim().toLowerCase()',
|
|
"keyGenerator lowercases and trims the email key component"
|
|
);
|
|
// Same Redis-store contract the bootstrap/reset/confirm-delete/delete-intent
|
|
// definitions pin below: in cluster mode a default MemoryStore would
|
|
// silently multiply each budget by the worker count, so the counters must
|
|
// share Redis when it is up and fail open when increment() rejects.
|
|
assertContains(
|
|
block,
|
|
"store: redisClient ? buildAssistantRedisStore() : undefined",
|
|
"shared Redis-backed store with a MemoryStore fallback when Redis is off at boot"
|
|
);
|
|
assertContains(block, "passOnStoreError: true", "fail open when increment() rejects (Redis down since boot)");
|
|
assertContains(block, "securityLog(", "handler logs via securityLog");
|
|
assertContains(block, "console.log(", "handler also console.logs");
|
|
assertContains(block, "status(429)", "answers 429 when exhausted");
|
|
assertContains(block, "code: \"", "429 body carries a machine code field");
|
|
}
|
|
});
|
|
|
|
test("completion limiter: per-session 20 and per-account 60 per 5 min, keyed email(+sid) without IP", () => {
|
|
const session = extractBlock(indexSource, "const dashboardAssistantCompletionSessionRateLimiter = rateLimit(");
|
|
const account = extractBlock(indexSource, "const dashboardAssistantCompletionAccountRateLimiter = rateLimit(");
|
|
assert.strictEqual(extractKeyTemplate(session), "assistant-completion-session:${email}:${sid}");
|
|
assert.strictEqual(extractKeyTemplate(account), "assistant-completion-account:${email}");
|
|
for (const block of [session, account]) {
|
|
assertContains(block, "windowMs: 5 * 60 * 1000", "5 minute window");
|
|
assertContains(block, "getRequestIp", "IP may appear in the security log line");
|
|
}
|
|
assertContains(session, "max: 20,", "per-session budget 20 (comma anchors the value against max: 20x)");
|
|
assertContains(account, "max: 60,", "per-account budget 60 (comma anchors the value)");
|
|
assertContains(session, 'code: "assistant-rate-limit"', "machine code assistant-rate-limit");
|
|
assertContains(account, 'code: "assistant-rate-limit"', "machine code assistant-rate-limit");
|
|
});
|
|
|
|
test("transcribe limiter: per-session 15 and per-account 45 per 5 min, keyed email(+sid) without IP", () => {
|
|
const session = extractBlock(indexSource, "const dashboardAssistantTranscribeSessionRateLimiter = rateLimit(");
|
|
const account = extractBlock(indexSource, "const dashboardAssistantTranscribeAccountRateLimiter = rateLimit(");
|
|
assert.strictEqual(extractKeyTemplate(session), "assistant-transcribe-session:${email}:${sid}");
|
|
assert.strictEqual(extractKeyTemplate(account), "assistant-transcribe-account:${email}");
|
|
assertContains(session, "windowMs: 5 * 60 * 1000", "5 minute window");
|
|
assertContains(account, "windowMs: 5 * 60 * 1000", "5 minute window");
|
|
assertContains(session, "max: 15,", "per-session budget 15 (comma anchors the value)");
|
|
assertContains(account, "max: 45,", "per-account budget 45 (comma anchors the value)");
|
|
assertContains(session, 'code: "transcribe-rate-limit"', "machine code transcribe-rate-limit");
|
|
assertContains(account, 'code: "transcribe-rate-limit"', "machine code transcribe-rate-limit");
|
|
});
|
|
|
|
test("models limiter: single 30 per 5 min per email+session (delete-intent style, no backstop)", () => {
|
|
const models = extractBlock(indexSource, "const dashboardAssistantModelsRateLimiter = rateLimit(");
|
|
assert.strictEqual(extractKeyTemplate(models), "assistant-models:${email}:${sid}");
|
|
assertContains(models, "windowMs: 5 * 60 * 1000", "5 minute window");
|
|
assertContains(models, "max: 30,", "per-session budget 30 (comma anchors the value)");
|
|
assertContains(models, 'code: "models-rate-limit"', "machine code models-rate-limit");
|
|
});
|
|
|
|
test("bootstrap/reset/confirm-delete/delete-intent/token/access limiters are always-on with the shared Redis store", () => {
|
|
// Same house pattern as the completion/transcribe/models definitions above,
|
|
// plus the PM2-cluster fix: in cluster mode every default MemoryStore would
|
|
// silently multiply each account-wide backstop by the worker count, so when
|
|
// Redis is up every limiter must share Redis counters (its OWN store
|
|
// instance — express-rate-limit rejects a shared one), fail-open on store
|
|
// errors, and never consult the operator-optional global toggle.
|
|
const definitions = [
|
|
"const dashboardAssistantDeleteIntentRateLimiter = rateLimit(",
|
|
"const dashboardAssistantResetSessionRateLimiter = rateLimit(",
|
|
"const dashboardAssistantResetAccountRateLimiter = rateLimit(",
|
|
"const dashboardAssistantBootstrapSessionRateLimiter = rateLimit(",
|
|
"const dashboardAssistantBootstrapAccountRateLimiter = rateLimit(",
|
|
"const dashboardAssistantConfirmDeleteSessionRateLimiter = rateLimit(",
|
|
"const dashboardAssistantConfirmDeleteAccountRateLimiter = rateLimit(",
|
|
"const dashboardAssistantTokenSessionRateLimiter = rateLimit(",
|
|
"const dashboardAssistantTokenAccountRateLimiter = rateLimit(",
|
|
"const dashboardAssistantAccessSessionRateLimiter = rateLimit(",
|
|
"const dashboardAssistantAccessAccountRateLimiter = rateLimit(",
|
|
];
|
|
for (const marker of definitions) {
|
|
const block = extractBlock(indexSource, marker);
|
|
assert.ok(!block.includes("rate_limiting"), `${marker} must not consult security.rate_limiting`);
|
|
assertContains(block, "standardHeaders: true", "RateLimit standard headers");
|
|
assertContains(block, "legacyHeaders: false", "no legacy headers");
|
|
assertContains(block, "skip: (req) => !req.session?.user", "skips anonymous requests (route auth gates reject those)");
|
|
assertContains(
|
|
block,
|
|
'String(req.session?.user || "anon").trim().toLowerCase()',
|
|
"keyGenerator lowercases and trims the email key component"
|
|
);
|
|
assertContains(
|
|
block,
|
|
"store: redisClient ? buildAssistantRedisStore() : undefined",
|
|
"shared Redis-backed store with a MemoryStore fallback when Redis is off at boot"
|
|
);
|
|
assertContains(block, "passOnStoreError: true", "fail open when increment() rejects (Redis down since boot)");
|
|
assertContains(block, "securityLog(", "handler logs via securityLog");
|
|
assertContains(block, "console.log(", "handler also console.logs");
|
|
assertContains(block, "status(429)", "answers 429 when exhausted");
|
|
assertContains(block, "code: \"", "429 body carries a machine code field");
|
|
}
|
|
});
|
|
|
|
test("bootstrap limiter: per-session 60 and per-account 180 per 5 min, keyed email(+sid) without IP", () => {
|
|
const session = extractBlock(indexSource, "const dashboardAssistantBootstrapSessionRateLimiter = rateLimit(");
|
|
const account = extractBlock(indexSource, "const dashboardAssistantBootstrapAccountRateLimiter = rateLimit(");
|
|
assert.strictEqual(extractKeyTemplate(session), "assistant-bootstrap-session:${email}:${sid}");
|
|
assert.strictEqual(extractKeyTemplate(account), "assistant-bootstrap-account:${email}");
|
|
assertContains(session, "windowMs: 5 * 60 * 1000", "5 minute window");
|
|
assertContains(account, "windowMs: 5 * 60 * 1000", "5 minute window");
|
|
assertContains(session, "max: 60,", "per-session budget 60 (comma anchors the value)");
|
|
assertContains(account, "max: 180,", "per-account budget 180 (comma anchors the value)");
|
|
assertContains(session, 'code: "bootstrap-rate-limit"', "machine code bootstrap-rate-limit");
|
|
assertContains(account, 'code: "bootstrap-rate-limit"', "machine code bootstrap-rate-limit");
|
|
});
|
|
|
|
test("reset limiter: per-session 10 and per-account 30 per 5 min, keyed email(+sid) without IP", () => {
|
|
const session = extractBlock(indexSource, "const dashboardAssistantResetSessionRateLimiter = rateLimit(");
|
|
const account = extractBlock(indexSource, "const dashboardAssistantResetAccountRateLimiter = rateLimit(");
|
|
assert.strictEqual(extractKeyTemplate(session), "assistant-reset-session:${email}:${sid}");
|
|
assert.strictEqual(extractKeyTemplate(account), "assistant-reset-account:${email}");
|
|
assertContains(session, "windowMs: 5 * 60 * 1000", "5 minute window");
|
|
assertContains(account, "windowMs: 5 * 60 * 1000", "5 minute window");
|
|
assertContains(session, "max: 10,", "per-session budget 10 (comma anchors the value)");
|
|
assertContains(account, "max: 30,", "per-account budget 30 (comma anchors the value)");
|
|
assertContains(session, 'code: "reset-rate-limit"', "machine code reset-rate-limit");
|
|
assertContains(account, 'code: "reset-rate-limit"', "machine code reset-rate-limit");
|
|
});
|
|
|
|
test("confirm-delete limiter: per-session 20 and per-account 60 per 5 min, keyed email(+sid) without IP", () => {
|
|
const session = extractBlock(indexSource, "const dashboardAssistantConfirmDeleteSessionRateLimiter = rateLimit(");
|
|
const account = extractBlock(indexSource, "const dashboardAssistantConfirmDeleteAccountRateLimiter = rateLimit(");
|
|
assert.strictEqual(extractKeyTemplate(session), "assistant-confirm-delete-session:${email}:${sid}");
|
|
assert.strictEqual(extractKeyTemplate(account), "assistant-confirm-delete-account:${email}");
|
|
assertContains(session, "windowMs: 5 * 60 * 1000", "5 minute window");
|
|
assertContains(account, "windowMs: 5 * 60 * 1000", "5 minute window");
|
|
assertContains(session, "max: 20,", "per-session budget 20 (comma anchors the value)");
|
|
assertContains(account, "max: 60,", "per-account budget 60 (comma anchors the value)");
|
|
assertContains(session, 'code: "confirm-delete-rate-limit"', "machine code confirm-delete-rate-limit");
|
|
assertContains(account, 'code: "confirm-delete-rate-limit"', "machine code confirm-delete-rate-limit");
|
|
});
|
|
|
|
test("token limiter: per-session 20 and per-account 60 per 5 min, keyed email(+sid) without IP", () => {
|
|
const session = extractBlock(indexSource, "const dashboardAssistantTokenSessionRateLimiter = rateLimit(");
|
|
const account = extractBlock(indexSource, "const dashboardAssistantTokenAccountRateLimiter = rateLimit(");
|
|
assert.strictEqual(extractKeyTemplate(session), "assistant-token-session:${email}:${sid}");
|
|
assert.strictEqual(extractKeyTemplate(account), "assistant-token-account:${email}");
|
|
assertContains(session, "windowMs: 5 * 60 * 1000", "5 minute window");
|
|
assertContains(account, "windowMs: 5 * 60 * 1000", "5 minute window");
|
|
assertContains(session, "max: 20,", "per-session budget 20 (comma anchors the value)");
|
|
assertContains(account, "max: 60,", "per-account budget 60 (comma anchors the value)");
|
|
// The generic assistant machine code, matching the completion limiters: the
|
|
// client renders the human error text either way.
|
|
assertContains(session, 'code: "assistant-rate-limit"', "machine code assistant-rate-limit");
|
|
assertContains(account, 'code: "assistant-rate-limit"', "machine code assistant-rate-limit");
|
|
});
|
|
|
|
test("access limiter: per-session 20 and per-account 60 per 5 min, keyed email(+sid) without IP", () => {
|
|
const session = extractBlock(indexSource, "const dashboardAssistantAccessSessionRateLimiter = rateLimit(");
|
|
const account = extractBlock(indexSource, "const dashboardAssistantAccessAccountRateLimiter = rateLimit(");
|
|
assert.strictEqual(extractKeyTemplate(session), "assistant-access-session:${email}:${sid}");
|
|
assert.strictEqual(extractKeyTemplate(account), "assistant-access-account:${email}");
|
|
assertContains(session, "windowMs: 5 * 60 * 1000", "5 minute window");
|
|
assertContains(account, "windowMs: 5 * 60 * 1000", "5 minute window");
|
|
assertContains(session, "max: 20,", "per-session budget 20 (comma anchors the value)");
|
|
assertContains(account, "max: 60,", "per-account budget 60 (comma anchors the value)");
|
|
assertContains(session, 'code: "assistant-rate-limit"', "machine code assistant-rate-limit");
|
|
assertContains(account, 'code: "assistant-rate-limit"', "machine code assistant-rate-limit");
|
|
});
|
|
|
|
test("delete-intent limiter: single 10 per 5 min per email+session (no account-wide backstop)", () => {
|
|
const intent = extractBlock(indexSource, "const dashboardAssistantDeleteIntentRateLimiter = rateLimit(");
|
|
assert.strictEqual(extractKeyTemplate(intent), "assistant-delete-intent:${email}:${sid}");
|
|
assertContains(intent, "windowMs: 5 * 60 * 1000", "5 minute window");
|
|
assertContains(intent, "max: 10,", "per-session budget 10 (comma anchors the value)");
|
|
assertContains(intent, 'code: "delete-intent-rate-limit"', "machine code delete-intent-rate-limit");
|
|
});
|
|
|
|
test("bootstrap/reset/confirm-delete/token/access compositions run the account-wide backstop first, then the per-session budget", () => {
|
|
for (const family of ["Bootstrap", "Reset", "ConfirmDelete", "Token", "Access"]) {
|
|
const composed = extractBlock(
|
|
indexSource,
|
|
`const dashboardAssistant${family}RateLimiter = function dashboardAssistant${family}RateLimiter`
|
|
);
|
|
const accountAt = composed.indexOf(`dashboardAssistant${family}AccountRateLimiter(req, res`);
|
|
const sessionAt = composed.indexOf(`dashboardAssistant${family}SessionRateLimiter(req, res, next)`);
|
|
assert.ok(accountAt >= 0 && sessionAt > accountAt,
|
|
`${family} composition: account backstop runs before the session budget`);
|
|
assertContains(
|
|
composed,
|
|
"if (backstopErr) return next(backstopErr);",
|
|
`${family} composition propagates a backstop error to next`
|
|
);
|
|
}
|
|
});
|
|
|
|
test("composed limiters run the account-wide backstop first, then the per-session budget", () => {
|
|
const completion = extractBlock(
|
|
indexSource,
|
|
"const dashboardAssistantCompletionRateLimiter = function dashboardAssistantCompletionRateLimiter"
|
|
);
|
|
const completionAccountAt = completion.indexOf("dashboardAssistantCompletionAccountRateLimiter(req, res");
|
|
const completionSessionAt = completion.indexOf("dashboardAssistantCompletionSessionRateLimiter(req, res, next)");
|
|
assert.ok(completionAccountAt >= 0 && completionSessionAt > completionAccountAt,
|
|
"completion composition: account backstop runs before the session budget");
|
|
// A store/limiter fault in the backstop must reach next() as an error, and
|
|
// the session budget must only run when the backstop passed.
|
|
assertContains(
|
|
completion,
|
|
"if (backstopErr) return next(backstopErr);",
|
|
"completion composition propagates a backstop error to next"
|
|
);
|
|
|
|
const transcribe = extractBlock(
|
|
indexSource,
|
|
"const dashboardAssistantTranscribeRateLimiter = function dashboardAssistantTranscribeRateLimiter"
|
|
);
|
|
const transcribeAccountAt = transcribe.indexOf("dashboardAssistantTranscribeAccountRateLimiter(req, res");
|
|
const transcribeSessionAt = transcribe.indexOf("dashboardAssistantTranscribeSessionRateLimiter(req, res, next)");
|
|
assert.ok(transcribeAccountAt >= 0 && transcribeSessionAt > transcribeAccountAt,
|
|
"transcribe composition: account backstop runs before the session budget");
|
|
assertContains(
|
|
transcribe,
|
|
"if (backstopErr) return next(backstopErr);",
|
|
"transcribe composition propagates a backstop error to next"
|
|
);
|
|
});
|
|
|
|
test("index.js wires the three quota limiters into the assistant router deps", () => {
|
|
const wiring = extractSlice(
|
|
indexSource,
|
|
"app.use(\"/api/dashboard-assistant\", createDashboardAssistantRouter({",
|
|
"}));"
|
|
);
|
|
for (const dep of [
|
|
"dashboardAssistantCompletionRateLimiter",
|
|
"dashboardAssistantTranscribeRateLimiter",
|
|
"dashboardAssistantModelsRateLimiter",
|
|
]) {
|
|
assertContains(wiring, dep, `wiring passes ${dep}`);
|
|
}
|
|
});
|
|
|
|
test("index.js wires the bootstrap/reset/confirm-delete/delete-intent/token/access limiters into the assistant router deps", () => {
|
|
const wiring = extractSlice(
|
|
indexSource,
|
|
"app.use(\"/api/dashboard-assistant\", createDashboardAssistantRouter({",
|
|
"}));"
|
|
);
|
|
for (const dep of [
|
|
"dashboardAssistantDeleteIntentRateLimiter",
|
|
"dashboardAssistantConfirmDeleteRateLimiter",
|
|
"dashboardAssistantResetRateLimiter",
|
|
"dashboardAssistantBootstrapRateLimiter",
|
|
"dashboardAssistantTokenRateLimiter",
|
|
"dashboardAssistantAccessRateLimiter",
|
|
]) {
|
|
assertContains(wiring, dep, `wiring passes ${dep}`);
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// routes/dashboard-assistant.js: the four routes mount their limiters
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("router: /chat and /client-follow-up mount the composed completion limiter", () => {
|
|
const chatRoute = extractSlice(routerSource, "router.post(\"/chat\"", "router.post(\"/client-follow-up\"");
|
|
const followUpRoute = extractSlice(routerSource, "router.post(\"/client-follow-up\"", "router.post(\"/delete-intent\"");
|
|
for (const [label, route] of [["/chat", chatRoute], ["/client-follow-up", followUpRoute]]) {
|
|
assertContains(route, "typeof deps.dashboardAssistantCompletionRateLimiter === \"function\"",
|
|
`${label}: typeof-guarded limiter mount`);
|
|
assertContains(route, "deps.dashboardAssistantCompletionRateLimiter", `${label}: limiter mounted`);
|
|
assertContains(route, ": (req, res, next) => next()", `${label}: no-op fallback when the dep is absent`);
|
|
}
|
|
});
|
|
|
|
test("router: /transcribe mounts the transcribe limiter BEFORE the auth gate and multer", () => {
|
|
const transcribeRoute = extractSlice(routerSource, "router.post(\"/transcribe\"", "router.post(\"/chat\"");
|
|
assertContains(transcribeRoute, "typeof deps.dashboardAssistantTranscribeRateLimiter === \"function\"",
|
|
"typeof-guarded limiter mount");
|
|
assertContains(transcribeRoute, "deps.dashboardAssistantTranscribeRateLimiter", "limiter mounted");
|
|
assertContains(transcribeRoute, ": (req, res, next) => next()", "no-op fallback when the dep is absent");
|
|
const limiterAt = transcribeRoute.indexOf("deps.dashboardAssistantTranscribeRateLimiter");
|
|
const authGateAt = transcribeRoute.indexOf("requireAssistantAccess(req, res)");
|
|
const multerAt = transcribeRoute.indexOf("upload.single(\"audio\")");
|
|
assert.ok(limiterAt >= 0 && authGateAt > limiterAt,
|
|
"the limiter is the first middleware of the chain");
|
|
assert.ok(multerAt > authGateAt,
|
|
"the auth gate still precedes multer (no upload buffering before both)");
|
|
});
|
|
|
|
test("router: /models mounts the models limiter with the same fallback style", () => {
|
|
const modelsRoute = extractSlice(routerSource, "router.get(\"/models\"", "router.post(\"/token\"");
|
|
assertContains(modelsRoute, "typeof deps.dashboardAssistantModelsRateLimiter === \"function\"",
|
|
"typeof-guarded limiter mount");
|
|
assertContains(modelsRoute, "deps.dashboardAssistantModelsRateLimiter", "limiter mounted");
|
|
assertContains(modelsRoute, ": (req, res, next) => next()", "no-op fallback when the dep is absent");
|
|
});
|
|
|
|
test("router: /bootstrap mounts the bootstrap limiter BEFORE the auth gate", () => {
|
|
const bootstrapRoute = extractSlice(routerSource, "router.get(\"/bootstrap\"", "router.get(\"/models\"");
|
|
assertContains(bootstrapRoute, "typeof deps.dashboardAssistantBootstrapRateLimiter === \"function\"",
|
|
"typeof-guarded limiter mount");
|
|
assertContains(bootstrapRoute, "deps.dashboardAssistantBootstrapRateLimiter", "limiter mounted");
|
|
assertContains(bootstrapRoute, ": (req, res, next) => next()", "no-op fallback when the dep is absent");
|
|
const limiterAt = bootstrapRoute.indexOf("deps.dashboardAssistantBootstrapRateLimiter");
|
|
const authGateAt = bootstrapRoute.indexOf("requireAssistantAccess(req, res)");
|
|
assert.ok(limiterAt >= 0 && authGateAt > limiterAt,
|
|
"the limiter is the first middleware of the chain, ahead of the handler's auth check");
|
|
});
|
|
|
|
test("router: /reset and /delete-intent mount their limiters with the same fallback style", () => {
|
|
const resetRoute = extractSlice(routerSource, "router.post(\"/reset\"", "router.post(\"/transcribe\"");
|
|
assertContains(resetRoute, "typeof deps.dashboardAssistantResetRateLimiter === \"function\"",
|
|
"/reset: typeof-guarded limiter mount");
|
|
assertContains(resetRoute, "deps.dashboardAssistantResetRateLimiter", "/reset: limiter mounted");
|
|
assertContains(resetRoute, ": (req, res, next) => next()", "/reset: no-op fallback when the dep is absent");
|
|
|
|
const intentRoute = extractSlice(routerSource, "router.post(\"/delete-intent\"", "router.post(\"/confirm-delete\"");
|
|
assertContains(intentRoute, "typeof deps.dashboardAssistantDeleteIntentRateLimiter === \"function\"",
|
|
"/delete-intent: typeof-guarded limiter mount");
|
|
assertContains(intentRoute, "deps.dashboardAssistantDeleteIntentRateLimiter", "/delete-intent: limiter mounted");
|
|
assertContains(intentRoute, ": (req, res, next) => next()", "/delete-intent: no-op fallback when the dep is absent");
|
|
});
|
|
|
|
test("router: /token and /access mount their limiters with the same fallback style", () => {
|
|
const tokenRoute = extractSlice(routerSource, "router.post(\"/token\"", "router.post(\"/access\"");
|
|
assertContains(tokenRoute, "typeof deps.dashboardAssistantTokenRateLimiter === \"function\"",
|
|
"/token: typeof-guarded limiter mount");
|
|
assertContains(tokenRoute, "deps.dashboardAssistantTokenRateLimiter", "/token: limiter mounted");
|
|
assertContains(tokenRoute, ": (req, res, next) => next()", "/token: no-op fallback when the dep is absent");
|
|
const tokenLimiterAt = tokenRoute.indexOf("deps.dashboardAssistantTokenRateLimiter");
|
|
const tokenAuthGateAt = tokenRoute.indexOf("requireAssistantAdmin(req, res)");
|
|
assert.ok(tokenLimiterAt >= 0 && tokenAuthGateAt > tokenLimiterAt,
|
|
"the /token limiter is the first middleware of the chain");
|
|
|
|
const accessRoute = extractSlice(routerSource, "router.post(\"/access\"", "router.post(\"/reset\"");
|
|
assertContains(accessRoute, "typeof deps.dashboardAssistantAccessRateLimiter === \"function\"",
|
|
"/access: typeof-guarded limiter mount");
|
|
assertContains(accessRoute, "deps.dashboardAssistantAccessRateLimiter", "/access: limiter mounted");
|
|
assertContains(accessRoute, ": (req, res, next) => next()", "/access: no-op fallback when the dep is absent");
|
|
const accessLimiterAt = accessRoute.indexOf("deps.dashboardAssistantAccessRateLimiter");
|
|
const accessAuthGateAt = accessRoute.indexOf("requireAssistantAdmin(req, res)");
|
|
assert.ok(accessLimiterAt >= 0 && accessAuthGateAt > accessLimiterAt,
|
|
"the /access limiter is the first middleware of the chain");
|
|
});
|
|
|
|
test("router: /confirm-delete mounts the confirm-loop budget AHEAD of the shared step-up credential limiter", () => {
|
|
const confirmRoute = extractSlice(routerSource, "router.post(\"/confirm-delete\"", "return router;");
|
|
assertContains(confirmRoute, "typeof deps.dashboardAssistantConfirmDeleteRateLimiter === \"function\"",
|
|
"typeof-guarded confirm-loop limiter mount");
|
|
assertContains(confirmRoute, "deps.dashboardAssistantConfirmDeleteRateLimiter", "confirm-loop limiter mounted");
|
|
assertContains(confirmRoute, "deps.sessionRevoke2faRateLimiter", "shared step-up credential limiter mounted");
|
|
assertContains(confirmRoute, ": (req, res, next) => next()", "no-op fallback when the dep is absent");
|
|
const confirmAt = confirmRoute.indexOf("deps.dashboardAssistantConfirmDeleteRateLimiter");
|
|
const stepUpAt = confirmRoute.indexOf("deps.sessionRevoke2faRateLimiter");
|
|
assert.ok(confirmAt >= 0 && stepUpAt > confirmAt,
|
|
"the every-attempt budget runs before the credential-bearing step-up limiter");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Behavioral: mounting semantics through a booted router
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const ADMIN_EMAIL = "admin@test.local";
|
|
|
|
// Boot the real router with minimal deps on a throwaway app, mirroring
|
|
// tests/dashboard-assistant-delete-flow.test.js. `extraDeps` layers injected
|
|
// limiters (or junk) on top of a deps object that OMITS them by default.
|
|
function bootApp({ sessionUser = ADMIN_EMAIL, extraDeps = {} } = {}) {
|
|
const session = { user: sessionUser };
|
|
let authCalls = 0;
|
|
|
|
const deps = {
|
|
isAuthenticated: async () => {
|
|
authCalls += 1;
|
|
return !!session.user;
|
|
},
|
|
isAdmin: async () => false,
|
|
getDashboardAssistantConfig: () => ({ allowNormalUsers: false }),
|
|
db: { query: async () => [] },
|
|
...extraDeps,
|
|
};
|
|
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use((req, res, next) => {
|
|
req.session = session;
|
|
req.sessionID = "test-sid-1";
|
|
next();
|
|
});
|
|
app.use("/api/dashboard-assistant", createDashboardAssistantRouter(deps));
|
|
|
|
const server = app.listen(0);
|
|
const base = `http://127.0.0.1:${server.address().port}/api/dashboard-assistant`;
|
|
|
|
const request = async (method, path, body) =>
|
|
fetch(`${base}${path}`, {
|
|
method,
|
|
headers: body === undefined ? {} : { "Content-Type": "application/json" },
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
});
|
|
|
|
const close = () => new Promise((resolve) => server.close(resolve));
|
|
return { session, authCalls: () => authCalls, request, close };
|
|
}
|
|
|
|
test("the router constructs and serves when deps omit the new limiters (fallback no-ops)", async () => {
|
|
const env = bootApp({ sessionUser: null });
|
|
try {
|
|
// Unauthenticated requests: the fallback no-op limiter passes through and
|
|
// the route auth gate rejects — no crash, no 500 from a missing limiter.
|
|
for (const [label, promise] of [
|
|
["POST /chat", env.request("POST", "/chat", { message: "hi" })],
|
|
["POST /client-follow-up", env.request("POST", "/client-follow-up", { summary: "done" })],
|
|
["POST /transcribe", env.request("POST", "/transcribe", { language: "en" })],
|
|
["GET /models", env.request("GET", "/models?provider=groq")],
|
|
]) {
|
|
const response = await promise;
|
|
assert.strictEqual(response.status, 401, `${label} still reaches the auth gate`);
|
|
}
|
|
} finally {
|
|
await env.close();
|
|
}
|
|
});
|
|
|
|
test("the typeof-fallback also covers non-function dep values", async () => {
|
|
const env = bootApp({
|
|
sessionUser: null,
|
|
extraDeps: {
|
|
dashboardAssistantCompletionRateLimiter: "not-a-function",
|
|
dashboardAssistantTranscribeRateLimiter: 42,
|
|
dashboardAssistantModelsRateLimiter: true,
|
|
},
|
|
});
|
|
try {
|
|
const models = await env.request("GET", "/models?provider=groq");
|
|
assert.strictEqual(models.status, 401, "a non-function limiter dep must not break the route");
|
|
} finally {
|
|
await env.close();
|
|
}
|
|
});
|
|
|
|
test("each route invokes its INJECTED limiter before the handler runs", async () => {
|
|
const limited = (marker) => (req, res) => res.status(429).json({ error: "limited", marker });
|
|
const env = bootApp({
|
|
extraDeps: {
|
|
dashboardAssistantCompletionRateLimiter: limited("completion"),
|
|
dashboardAssistantTranscribeRateLimiter: limited("transcribe"),
|
|
dashboardAssistantModelsRateLimiter: limited("models"),
|
|
},
|
|
});
|
|
try {
|
|
const chat = await env.request("POST", "/chat", { message: "hi" });
|
|
assert.strictEqual(chat.status, 429, "the injected completion limiter answers for /chat");
|
|
assert.strictEqual((await chat.json()).marker, "completion");
|
|
assert.strictEqual(env.authCalls(), 0, "/chat never reached the auth gate behind the limiter");
|
|
|
|
const followUp = await env.request("POST", "/client-follow-up", { summary: "done" });
|
|
assert.strictEqual(followUp.status, 429, "the injected completion limiter answers for /client-follow-up");
|
|
assert.strictEqual((await followUp.json()).marker, "completion");
|
|
|
|
const models = await env.request("GET", "/models?provider=groq");
|
|
assert.strictEqual(models.status, 429, "the injected models limiter answers for /models");
|
|
assert.strictEqual((await models.json()).marker, "models");
|
|
assert.strictEqual(env.authCalls(), 0, "/models never reached the auth gate behind the limiter");
|
|
} finally {
|
|
await env.close();
|
|
}
|
|
});
|
|
|
|
test("the /transcribe limiter runs BEFORE the auth gate (and therefore before multer)", async () => {
|
|
const env = bootApp({
|
|
// Unauthenticated session: if the limiter were mounted after the auth
|
|
// gate, the gate would 401 before the limiter ever ran.
|
|
sessionUser: null,
|
|
extraDeps: {
|
|
dashboardAssistantTranscribeRateLimiter: (req, res) =>
|
|
res.status(429).json({ error: "limited", marker: "transcribe" }),
|
|
},
|
|
});
|
|
try {
|
|
const response = await env.request("POST", "/transcribe", { language: "en" });
|
|
assert.strictEqual(response.status, 429, "the limiter answers before the auth gate can 401");
|
|
assert.strictEqual((await response.json()).marker, "transcribe");
|
|
assert.strictEqual(env.authCalls(), 0, "the auth gate never ran, so multer never buffered anything");
|
|
} finally {
|
|
await env.close();
|
|
}
|
|
});
|
|
|
|
test("the fallback no-op keeps /bootstrap, /reset, /delete-intent, /confirm-delete, /token and /access serving to the auth gate", async () => {
|
|
const env = bootApp({ sessionUser: null });
|
|
try {
|
|
// Unauthenticated requests: the fallback no-op limiter passes through and
|
|
// the route auth gate rejects — no crash, no 500 from a missing limiter.
|
|
for (const [label, promise] of [
|
|
["GET /bootstrap", env.request("GET", "/bootstrap")],
|
|
["POST /reset", env.request("POST", "/reset")],
|
|
["POST /delete-intent", env.request("POST", "/delete-intent", { chatId: 1, server: "web-1" })],
|
|
["POST /confirm-delete", env.request("POST", "/confirm-delete", { chatId: 1, server: "web-1", intentId: "a".repeat(32) })],
|
|
["POST /token", env.request("POST", "/token", { provider: "groq", token: "" })],
|
|
["POST /access", env.request("POST", "/access", { allowNormalUsers: true })],
|
|
]) {
|
|
const response = await promise;
|
|
assert.strictEqual(response.status, 401, `${label} still reaches the auth gate`);
|
|
}
|
|
} finally {
|
|
await env.close();
|
|
}
|
|
});
|
|
|
|
test("each new route invokes its INJECTED limiter before the handler runs", async () => {
|
|
const limited = (marker) => (req, res) => res.status(429).json({ error: "limited", marker });
|
|
const env = bootApp({
|
|
extraDeps: {
|
|
dashboardAssistantBootstrapRateLimiter: limited("bootstrap"),
|
|
dashboardAssistantResetRateLimiter: limited("reset"),
|
|
dashboardAssistantDeleteIntentRateLimiter: limited("delete-intent"),
|
|
dashboardAssistantConfirmDeleteRateLimiter: limited("confirm-delete"),
|
|
dashboardAssistantTokenRateLimiter: limited("token"),
|
|
dashboardAssistantAccessRateLimiter: limited("access"),
|
|
},
|
|
});
|
|
try {
|
|
const bootstrap = await env.request("GET", "/bootstrap");
|
|
assert.strictEqual(bootstrap.status, 429, "the injected bootstrap limiter answers for /bootstrap");
|
|
assert.strictEqual((await bootstrap.json()).marker, "bootstrap");
|
|
assert.strictEqual(env.authCalls(), 0, "/bootstrap never reached the auth gate behind the limiter");
|
|
|
|
const reset = await env.request("POST", "/reset");
|
|
assert.strictEqual(reset.status, 429, "the injected reset limiter answers for /reset");
|
|
assert.strictEqual((await reset.json()).marker, "reset");
|
|
|
|
const deleteIntent = await env.request("POST", "/delete-intent", { chatId: 1, server: "web-1" });
|
|
assert.strictEqual(deleteIntent.status, 429, "the injected delete-intent limiter answers for /delete-intent");
|
|
assert.strictEqual((await deleteIntent.json()).marker, "delete-intent");
|
|
|
|
const confirmDelete = await env.request("POST", "/confirm-delete", {
|
|
chatId: 1,
|
|
server: "web-1",
|
|
intentId: "a".repeat(32),
|
|
currentPassword: "pw",
|
|
});
|
|
assert.strictEqual(confirmDelete.status, 429, "the injected confirm-delete limiter answers for /confirm-delete");
|
|
assert.strictEqual((await confirmDelete.json()).marker, "confirm-delete");
|
|
assert.strictEqual(env.authCalls(), 0, "/confirm-delete never reached the auth gate behind the limiter");
|
|
|
|
const token = await env.request("POST", "/token", { provider: "groq", token: "key" });
|
|
assert.strictEqual(token.status, 429, "the injected token limiter answers for /token");
|
|
assert.strictEqual((await token.json()).marker, "token");
|
|
|
|
const access = await env.request("POST", "/access", { allowNormalUsers: true });
|
|
assert.strictEqual(access.status, 429, "the injected access limiter answers for /access");
|
|
assert.strictEqual((await access.json()).marker, "access");
|
|
assert.strictEqual(env.authCalls(), 0, "/token and /access never reached the auth gate behind the limiter");
|
|
} finally {
|
|
await env.close();
|
|
}
|
|
});
|