Files
Kelx/tests/activity-log-cache.test.js
2026-11-30 16:32:37 +00:00

238 lines
10 KiB
JavaScript

"use strict";
// Tests for the activity-log reader hardening in index.js (bounded parsed-
// entry cache + dedicated always-on rate limiter + env-derived 413 cap).
//
// The cache (createActivityLogEntryCache) is what keeps a low-priv user from
// pinning the event loop with repeated /api/server/:name/activity hits: the
// endpoint used to re-read up to the whole log file and JSON.parse tens of
// thousands of lines on every request. This file pins, by real execution of
// the extracted factory (same technique as editor-marker-contract /
// file-action-token-mint-gates):
// - LRU eviction under BOTH bounds (server count and total entries), with
// recency refreshed on every hit;
// - the TTL being measured from parse time (hits do NOT extend it);
// - stat (mtime+size) invalidation and the per-server read-through cap;
// - source assertions that the route actually wires the cache and limiter
// in (middleware order, cache set only after a successful read) and that
// the 413 reader cap derives from ACTIVITY_LOG_MAX_SIZE, so the factory
// and the route can never drift apart.
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 ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
function extractRegion(source, startMarker, endMarker, label) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `${label}: start marker not found: ${startMarker}`);
const end = source.indexOf(endMarker, start);
assert.ok(end > start, `${label}: end marker not found after start: ${endMarker}`);
return source.slice(start, end);
}
// --- the factory under test, extracted from index.js and really executed ---
const cacheRegion = extractRegion(
indexSource,
"const ACTIVITY_LOG_READER_CACHE_TTL_MS = 5000;",
"const activityLogEntryCache = createActivityLogEntryCache();",
"index.js activity-log cache block"
);
const sandbox = {};
vm.createContext(sandbox);
vm.runInContext(cacheRegion, sandbox);
const createActivityLogEntryCache = sandbox.createActivityLogEntryCache;
function makeClock(start) {
let t = start;
return { now: () => t, advance: (ms) => { t += ms; } };
}
// --- 1. LRU eviction: server-count bound + recency refresh on hit ---
test("evicts least-recently-used server when the server-count bound is exceeded", () => {
const cache = createActivityLogEntryCache({
maxServers: 3, maxTotalEntries: 1000, maxEntriesPerServer: 500,
});
cache.set("alpha", 1, 10, [{ i: 1 }]);
cache.set("bravo", 2, 10, [{ i: 2 }]);
cache.set("charlie", 3, 10, [{ i: 3 }]);
// alpha is oldest, but touching it refreshes its recency.
assert.ok(cache.get("alpha", 1, 10), "alpha should be a cache hit before eviction");
cache.set("delta", 4, 10, [{ i: 4 }]); // 4 servers > 3 -> evict LRU (bravo)
assert.ok(cache.get("alpha", 1, 10), "recently-touched alpha must survive");
assert.equal(cache.get("bravo", 2, 10), undefined, "LRU bravo must be evicted");
assert.ok(cache.get("charlie", 3, 10), "charlie must survive");
assert.ok(cache.get("delta", 4, 10), "the just-set entry must survive");
assert.equal(cache.size(), 3);
});
// --- 2. LRU eviction: total-entry bound across servers ---
test("evicts whole least-recently-used servers until total entries is under the cap", () => {
const cache = createActivityLogEntryCache({
maxServers: 10, maxTotalEntries: 10, maxEntriesPerServer: 500,
});
cache.set("big-old", 1, 10, Array.from({ length: 6 }, (_, i) => ({ i })));
cache.set("small-new", 2, 10, Array.from({ length: 5 }, (_, i) => ({ i })));
// 6 + 5 = 11 > 10 -> the older server is evicted whole (entries arrays are
// never sliced inside the cache; pagination slices outside it).
assert.equal(cache.get("big-old", 1, 10), undefined, "LRU server evicted");
assert.ok(cache.get("small-new", 2, 10), "newer server kept");
assert.equal(cache.totalEntries(), 5);
assert.equal(cache.size(), 1);
});
test("eviction terminates even if one entry set alone violates the total cap", () => {
const cache = createActivityLogEntryCache({
maxServers: 10, maxTotalEntries: 5, maxEntriesPerServer: 10,
});
cache.set("lonely", 1, 10, Array.from({ length: 8 }, (_, i) => ({ i })));
assert.equal(cache.totalEntries(), 0, "cannot satisfy cap -> evicted to empty");
assert.equal(cache.size(), 0);
});
// --- 3. TTL: measured from parse time, hits do not extend it ---
test("entries expire after the TTL measured from parse time, not last hit", () => {
const clock = makeClock(0);
const cache = createActivityLogEntryCache({
ttlMs: 5000, maxServers: 10, maxTotalEntries: 1000, maxEntriesPerServer: 500,
now: clock.now,
});
cache.set("srv", 1, 10, [{ i: 1 }]);
clock.advance(4000);
assert.ok(cache.get("srv", 1, 10), "hit inside TTL");
clock.advance(999);
assert.ok(cache.get("srv", 1, 10), "hit at 4999ms since parse");
clock.advance(1);
assert.equal(cache.get("srv", 1, 10), undefined, "expired at 5000ms since parse");
assert.equal(cache.size(), 0, "expired entry is dropped, not left to linger");
});
// --- 4. stat invalidation: mtime+size must both match ---
test("a changed mtime or size invalidates the entry (flushed/appended file)", () => {
const cache = createActivityLogEntryCache({
maxServers: 10, maxTotalEntries: 1000, maxEntriesPerServer: 500,
});
const entries = [{ i: 1 }, { i: 2 }];
cache.set("srv", 100.5, 50, entries);
assert.strictEqual(cache.get("srv", 100.5, 50), entries, "matching mtime+size hits");
assert.equal(cache.get("srv", 101.5, 50), undefined, "mtime mismatch misses");
assert.equal(cache.get("srv", 100.5, 51), undefined, "size mismatch misses");
assert.equal(cache.size(), 0, "a mismatched lookup drops the stale entry");
});
// --- 5. per-server read-through cap + identity semantics ---
test("parses above the per-server cap are refused (read-through), arrays kept as-is", () => {
const cache = createActivityLogEntryCache({
maxServers: 10, maxTotalEntries: 1000, maxEntriesPerServer: 3,
});
const tooBig = Array.from({ length: 4 }, (_, i) => ({ i }));
assert.equal(cache.set("huge", 1, 10, tooBig), false, "oversized parse refused");
assert.equal(cache.get("huge", 1, 10), undefined);
const ok = [{ a: 1 }];
assert.equal(cache.set("ok", 1, 10, ok), true);
assert.strictEqual(cache.get("ok", 1, 10), ok, "same array identity: unfiltered, never copied");
assert.equal(cache.set("ok", 1, 10, "not-an-array"), false, "non-array refused");
});
test("the module-scope instance uses the real default bounds", () => {
const cache = createActivityLogEntryCache();
assert.equal(cache.set("srv", 1, 1, Array.from({ length: 50000 }, (_, i) => ({ i }))), true);
assert.equal(cache.set("srv2", 1, 1, Array.from({ length: 50001 }, (_, i) => ({ i }))), false);
assert.equal(cache.totalEntries(), 50000);
});
// --- 6. source pins: the route must keep wiring cache + limiter + cap in ---
const routeRegion = extractRegion(
indexSource,
'app.get("/api/server/:name/activity", rejectCrossSiteRead, activityLogRateLimiter',
'app.post("/api/servers/statuses"',
"index.js activity route"
);
test("route middleware order is rejectCrossSiteRead, activityLogRateLimiter, handler", () => {
assert.ok(
indexSource.includes(
'app.get("/api/server/:name/activity", rejectCrossSiteRead, activityLogRateLimiter, async (req, res) => {'
),
"the rate limiter must sit between rejectCrossSiteRead and the handler"
);
});
test("route consults the cache with the fresh stat and stores only after a successful read", () => {
assert.ok(
routeRegion.includes("activityLogEntryCache.get(serverName, st.mtimeMs, st.size)"),
"cache lookup must be keyed by the fresh stat mtime+size"
);
assert.ok(
routeRegion.includes("activityLogEntryCache.set(serverName, st.mtimeMs, st.size, parsed)"),
"cache store must use the same stat the read was validated against"
);
const readAt = routeRegion.indexOf('await fsp.readFile(logPath, "utf8")');
const setAt = routeRegion.indexOf("activityLogEntryCache.set(");
assert.ok(readAt >= 0 && setAt > readAt, "cache set must happen AFTER the read");
assert.doesNotMatch(routeRegion, /10 \* 1024 \* 1024/, "hardcoded 10MB cap must be gone");
assert.ok(
routeRegion.includes("st.size > ACTIVITY_LOG_READER_MAX_BYTES"),
"413 check must use the env-derived reader cap"
);
});
test("reader cap derives from ACTIVITY_LOG_MAX_SIZE (nodes.js rotation threshold) plus 1MB slack", () => {
assert.match(
indexSource,
/const ACTIVITY_LOG_READER_MAX_BYTES =\s*\n\s*\(parseInt\(process\.env\.ACTIVITY_LOG_MAX_SIZE \|\| "", 10\) \|\| 5 \* 1024 \* 1024\) \+ 1024 \* 1024;/,
"the cap must mirror nodes.js ACTIVITY_LOG_MAX_SIZE (default 5MB) plus 1MB slack"
);
assert.ok(
indexSource.includes("ACTIVITY_LOG_REQUESTS_PER_MIN"),
"the limiter budget must be env-tunable"
);
assert.match(
indexSource,
/keyGenerator: \(req\) => `activity:\$\{ipKeyGenerator\(String\(getRequestIp\(req\) \|\| "unknown"\)\)\}:\$\{req\.session\?\.user \|\| 'anon'\}`/,
"limiter must be keyed per IP+session (IP part /56-bucketed via ipKeyGenerator, session-user part verbatim)"
);
assert.match(
indexSource,
/skip: \(req\) => isRequestFromTrustedSubnet\(req\),\s*\n\s*handler: \(req, res\) => \{\s*\n\s*res\.status\(429\)\.json\(\{ error: "Too many activity log requests, please slow down\." \}\);/,
"limiter must keep the trusted-subnet bypass and JSON 429 handler"
);
});
test("default cache bounds stay at 25 servers / 100k total entries / 50k per server / 5s TTL", () => {
assert.match(indexSource, /const ACTIVITY_LOG_READER_CACHE_TTL_MS = 5000;/);
assert.match(indexSource, /const ACTIVITY_LOG_READER_CACHE_MAX_SERVERS = 25;/);
assert.match(indexSource, /const ACTIVITY_LOG_READER_CACHE_MAX_TOTAL_ENTRIES = 100000;/);
assert.match(indexSource, /const ACTIVITY_LOG_READER_CACHE_MAX_ENTRIES_PER_SERVER = 50000;/);
assert.ok(
indexSource.includes("per-user filtering"),
"the per-user filtering hook comment must mark where later waves plug in"
);
});