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

321 lines
14 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";
// Tests for utils/activity-log-name.js — the injective filename key for
// per-server activity logs, introduced to fix a cross-tenant information
// disclosure: the old transform `name.replace(/[^a-zA-Z0-9_-]/g, "_")` was
// NOT injective, so servers "shop.bot" and "shop_bot" (names legally differ —
// sanitizeServerToken keeps [A-Za-z0-9\-_.]) shared ONE log file while the
// access check authorized the raw requested name. One tenant could read the
// other's full audit trail (console commands, paths, actor emails, IPs).
//
// This file pins:
// - the collision pair producing DIFFERENT keys (the regression itself);
// - injectivity over a fixed corpus AND a deterministic pseudo-random fuzz
// (verified two ways: keys are distinct, and a reference decoder written
// against the documented format round-trips every non-truncated key —
// a decodable encoding of distinct inputs IS injective);
// - the key charset staying filesystem-safe ([A-Za-z0-9_-] only, identical
// to the old scheme so extension/rotation/pruning keep working);
// - the length cap: two long names sharing a >160-char prefix (the
// truncation boundary) still get different keys via the sha256 suffix,
// including a cut landing mid-escape;
// - legacyActivityLogFileKey matching the OLD collapse exactly (the reader's
// read-only fallback must see exactly the pre-fix filenames);
// - source pins that nodes.js (writer + rotation) and the index.js reader
// route actually use the util and the guarded legacy fallback — same
// extraction technique as tests/activity-log-cache.test.js.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const { activityLogFileKey, legacyActivityLogFileKey } = require("./activity-log-name");
const ROOT = path.join(__dirname, "..");
const NODES_JS = fs.readFileSync(path.join(ROOT, "nodes.js"), "utf8");
const INDEX_JS = fs.readFileSync(path.join(ROOT, "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);
}
// --- 1. the regression: the collision pair must split -----------------------
test("the original collision pair gets different keys", () => {
assert.notStrictEqual(activityLogFileKey("shop.bot"), activityLogFileKey("shop_bot"));
// ...and the exact encodings are pinned so the format cannot drift silently.
assert.strictEqual(activityLogFileKey("shop.bot"), "shop_2e_bot");
assert.strictEqual(activityLogFileKey("shop_bot"), "shop__bot");
});
test("empty and whitespace-only names key to the empty string", () => {
assert.strictEqual(activityLogFileKey(""), "");
assert.strictEqual(activityLogFileKey(null), "");
assert.strictEqual(activityLogFileKey(undefined), "");
assert.strictEqual(activityLogFileKey(" "), "");
assert.strictEqual(legacyActivityLogFileKey(""), "");
assert.strictEqual(legacyActivityLogFileKey(null), "");
});
// --- 2. injectivity over a fixed corpus --------------------------------------
const CORPUS = [
"_system", "MyBot", "mybot", "a_b", "a__b", "a.b", "a..b",
"user@example.com", "s p a c e", "сервер", "🤖", "x/y", "..", "-",
"_", "__", "___", "____", "a-", "-a", "--",
"Shop.Bot", "SHOP_BOT", "shop__bot", "shop.bot.", ".shop.bot",
"🤖bot", "bot🤖", "с_ервер", "a b", "a b", "a_b_", "_a_b",
"shop.bot", "shop_bot", "a_b.c", "a.b_c", "server-1", "server_1",
"tab\tname", "nl\nname", "café", "中文", "x y z", "....", "----",
];
test("every distinct corpus input maps to a distinct key", () => {
const byKey = new Map();
for (const input of CORPUS) {
const key = activityLogFileKey(input);
const other = byKey.get(key);
assert.ok(
other === undefined,
`key collision: ${JSON.stringify(input)} and ${JSON.stringify(other)} both -> ${key}`
);
byKey.set(key, input);
}
});
test("keys are trimmed-input injective and the trim itself is pinned", () => {
// The key is defined over the TRIMMED name (callers pass sanitizeServerToken
// output, which is already trimmed); distinct trimmed inputs must not share
// a key even when the raw strings differ only by surrounding whitespace.
assert.strictEqual(activityLogFileKey(" shop.bot "), activityLogFileKey("shop.bot"));
const byKey = new Map();
for (const input of CORPUS) {
const trimmed = String(input).trim();
const key = activityLogFileKey(trimmed);
const other = byKey.get(key);
assert.ok(other === undefined, `trimmed-input collision on ${JSON.stringify(trimmed)}`);
byKey.set(key, trimmed);
}
});
// --- 3. injectivity over a deterministic fuzz corpus, proven by decoding -----
// Reference decoder for the documented format (per code point: "_" -> "__",
// [A-Za-z0-9-] -> itself, anything else -> "_<hex>_"). If decode(encode(x))
// === x for every input, distinct inputs cannot share a key: a shared key
// would decode to two different originals.
function decodeKey(key) {
let out = "";
for (let i = 0; i < key.length; i++) {
if (key[i] !== "_") {
assert.match(key[i], /^[A-Za-z0-9-]$/, "passthrough chars stay unchanged");
out += key[i];
continue;
}
if (key[i + 1] === "_") {
out += "_";
i++;
continue;
}
const end = key.indexOf("_", i + 1);
assert.ok(end > i + 1, "hex escape always contains at least one hex digit");
assert.match(key.slice(i + 1, end), /^[0-9a-f]+$/, "escape payload is lowercase hex");
out += String.fromCodePoint(parseInt(key.slice(i + 1, end), 16));
i = end;
}
return out;
}
function lcg(seed) {
let s = seed >>> 0;
return () => {
s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
return s / 4294967296;
};
}
const FUZZ_ALPHABET = ["a", "B", "7", "-", "_", ".", "@", " ", "/", ":", "я", "é", "🤖", "\t", "..", "__"];
test("fuzz: 4000 generated names get distinct, filesystem-safe, decodable keys", () => {
const rand = lcg(0xa110c4);
const seenInputs = new Set(); // trimmed input -> dedupe (the LCG repeats itself)
const seen = new Map(); // key -> trimmed input
let generated = 0;
for (let i = 0; i < 4000; i++) {
const len = 1 + Math.floor(rand() * 24);
let s = "";
for (let j = 0; j < len; j++) s += FUZZ_ALPHABET[Math.floor(rand() * FUZZ_ALPHABET.length)];
const input = s.trim();
if (!input) continue; // whitespace-only fuzz strings all trim to ""
if (seenInputs.has(input)) continue; // same input twice is not a collision
seenInputs.add(input);
generated++;
const key = activityLogFileKey(input);
const other = seen.get(key);
assert.ok(
other === undefined,
`fuzz collision: ${JSON.stringify(input)} and ${JSON.stringify(other)} both -> ${key}`
);
seen.set(key, input);
assert.match(key, /^[A-Za-z0-9_-]*$/, `key for ${JSON.stringify(input)} is filesystem-safe`);
if (key.length <= 240) {
assert.strictEqual(decodeKey(key), input, `key for ${JSON.stringify(input)} round-trips`);
}
}
assert.ok(generated > 3000, "fuzz actually exercised a large corpus");
});
// --- 4. charset + length cap --------------------------------------------------
test("keys never contain characters outside [A-Za-z0-9_-]", () => {
for (const input of CORPUS) {
assert.match(activityLogFileKey(input), /^[A-Za-z0-9_-]*$/, JSON.stringify(input));
}
assert.match(activityLogFileKey("сервер"), /^[A-Za-z0-9_-]+$/);
assert.match(activityLogFileKey("🤖"), /^[A-Za-z0-9_-]+$/);
});
test("long names sharing a 300-char prefix still get different keys (truncation + hash)", () => {
const longA = "a".repeat(300) + "X";
const longB = "a".repeat(300) + "Y";
const keyA = activityLogFileKey(longA);
const keyB = activityLogFileKey(longB);
assert.notStrictEqual(keyA, keyB);
// Both are truncated with the same 160-char head; the sha256 suffix over the
// FULL encoding is what keeps them apart.
assert.strictEqual(keyA.slice(0, 160), keyB.slice(0, 160));
assert.match(keyA, /^[A-Za-z0-9_-]{160}-[0-9a-f]{12}$/, "truncated key is 160 chars + '-' + 12 hex chars");
assert.ok(keyA.length <= 160 + 1 + 12, "truncated key is bounded at 173 chars");
});
test("a truncation cut landing mid-escape still separates two long names", () => {
// "a" x159 then "." : the encoded form is 159 passthrough chars followed by
// "_2e_...", so encoded.slice(0, 160) ends INSIDE the hex escape ("_2").
const midA = "a".repeat(159) + "." + "a";
const midB = "a".repeat(159) + "." + "b";
const keyA = activityLogFileKey(midA);
const keyB = activityLogFileKey(midB);
assert.notStrictEqual(keyA, keyB, "the hash covers the cut-off part, so no collision");
});
// --- 5. _system and the legacy key --------------------------------------------
test("_system keeps working: new key is __system, legacy key stays _system", () => {
assert.strictEqual(activityLogFileKey("_system"), "__system");
assert.strictEqual(legacyActivityLogFileKey("_system"), "_system");
assert.notStrictEqual(activityLogFileKey("_system"), legacyActivityLogFileKey("_system"));
});
test("legacy key matches the OLD collapse exactly (pinned examples)", () => {
// The writer's callers always passed sanitizeServerToken output (already
// trimmed, charset [A-Za-z0-9\-_.]), so trimming first changes nothing for
// real names — and these pins must match the pre-fix filenames on disk.
assert.strictEqual(legacyActivityLogFileKey("shop.bot"), "shop_bot");
assert.strictEqual(legacyActivityLogFileKey("shop_bot"), "shop_bot"); // the old collision, verbatim
assert.strictEqual(legacyActivityLogFileKey("My Bot"), "My_Bot");
assert.strictEqual(legacyActivityLogFileKey("_system"), "_system");
assert.strictEqual(legacyActivityLogFileKey("a-b_c"), "a-b_c");
assert.strictEqual(legacyActivityLogFileKey("user@example.com"), "user_example_com");
});
// --- 6. source pins: writer, rotation and reader must use the util ------------
const getActivityLogPathRegion = extractRegion(
NODES_JS,
"function getActivityLogPath",
"function validatePortInput",
"nodes.js getActivityLogPath"
);
const rotateRegion = extractRegion(
NODES_JS,
"async function rotateActivityLogIfNeeded",
"function requeueFailedActivityLogEntries",
"nodes.js rotateActivityLogIfNeeded"
);
const activityRouteRegion = extractRegion(
INDEX_JS,
'app.get("/api/server/:name/activity"',
'app.post("/api/servers/statuses"',
"index.js activity route"
);
const invalidateIndexRegion = extractRegion(
INDEX_JS,
"function invalidateServerIndexCache()",
"async function saveServersIndex",
"index.js invalidateServerIndexCache"
);
test("nodes.js writer keys files with the injective key, not the collapse", () => {
assert.ok(
NODES_JS.includes('require("./utils/activity-log-name")'),
"nodes.js must require the util"
);
assert.ok(
getActivityLogPathRegion.includes("${activityLogFileKey(serverName)}.log"),
"getActivityLogPath must build the filename from activityLogFileKey"
);
assert.doesNotMatch(
getActivityLogPathRegion,
/replace\(\/\[\^a-zA-Z0-9_-\]\/g/,
"the collapsing transform must be gone from the writer"
);
});
test("nodes.js rotation prunes by the SAME key plus the legacy prefix", () => {
const keyAt = rotateRegion.indexOf("const key = activityLogFileKey(serverName);");
const legacyAt = rotateRegion.indexOf("const legacyKey = legacyActivityLogFileKey(serverName);");
assert.ok(keyAt >= 0, "rotation must derive the current key");
assert.ok(legacyAt >= 0, "rotation must derive the legacy key for pre-fix files");
assert.ok(
rotateRegion.includes("isRotated(f, key)") && rotateRegion.includes("isRotated(f, legacyKey)"),
"the pruning filter must match BOTH prefixes (new + legacy)"
);
assert.ok(
rotateRegion.includes("f !== `${key}.log`") && rotateRegion.includes("f !== `${legacyKey}.log`"),
"the live files (new and legacy) must be excluded from pruning"
);
});
test("index.js reader resolves canonically and falls back only through the ambiguity guard", () => {
assert.ok(
activityRouteRegion.includes("const resolvedServer = await findServer(serverName).catch(() => null);"),
"the route must resolve the requested name with the shared findServer helper"
);
assert.ok(
activityRouteRegion.includes("getCanonicalServerName(resolvedServer, serverName) || serverName"),
"the file key must come from the resolved row's canonical name, with the sanitized request as fallback"
);
assert.ok(
activityRouteRegion.includes("activityLogFileKey(canonicalName)"),
"the primary file must use the injective key of the canonical name"
);
assert.ok(
activityRouteRegion.includes("legacyActivityLogFileIsUnambiguous(legacyKey, canonicalName)"),
"the legacy file may only be read through the ambiguity guard"
);
assert.doesNotMatch(
activityRouteRegion,
/replace\(\/\[\^a-zA-Z0-9_-\]\/g/,
"the collapsing transform must be gone from the reader"
);
assert.ok(
invalidateIndexRegion.includes("invalidateActivityLogLegacyAmbiguityCache()"),
"server-index invalidation must also drop the ambiguity verdicts"
);
// Auth order (previous hardening wave) must be untouched: authenticate ->
// authorize -> perms, all BEFORE any file resolution.
const authAt = activityRouteRegion.indexOf("await isAuthenticated(req)");
const accessAt = activityRouteRegion.indexOf("await userHasAccessToServer(email, serverName)");
const permsAt = activityRouteRegion.indexOf("perms.activity_logs");
const resolveAt = activityRouteRegion.indexOf("await findServer(serverName)");
assert.ok(authAt >= 0 && accessAt > authAt && permsAt > accessAt, "auth chain order unchanged");
assert.ok(resolveAt > permsAt, "canonical resolution happens only after the auth chain");
});