317 lines
16 KiB
JavaScript
317 lines
16 KiB
JavaScript
"use strict";
|
|
|
|
// Tests for the per-user filtering hook in the activity-log reader route
|
|
// (index.js, /api/server/:name/activity): console-command gating +
|
|
// defense-in-depth URL query redaction.
|
|
//
|
|
// Security context: reading the activity log requires only activity_logs,
|
|
// which is independent of console_read/console_write. Without gating, a user
|
|
// granted ONLY activity_logs could read the verbatim `{ command }` history of
|
|
// every console_command entry (passwords, tokens, API keys pasted at setup
|
|
// prompts — scheduler-sent commands are the same class), making activity_logs
|
|
// a superset of console_read for historical input. The hook therefore:
|
|
// 1. strips action === "console_command" entries for viewers without
|
|
// console_read (admins keep everything);
|
|
// 2. redacts the query string of any string details.url for EVERY viewer
|
|
// (presigned/upload URLs carry signature/token credentials in the query;
|
|
// the write side now strips it, this covers pre-fix entries and writer
|
|
// regressions);
|
|
// 3. masks each entry's user to the email LOCAL PART for every viewer
|
|
// (full emails are login identifiers and co-users holding activity_logs
|
|
// must not receive them; non-email actors like "scheduler" pass through);
|
|
// 4. paginates and counts on the FILTERED array so offsets never point into
|
|
// hidden entries;
|
|
// and, because the parsed-entry cache (activityLogEntryCache) is shared across
|
|
// viewers, it must never mutate the cached array or its entry objects.
|
|
//
|
|
// Technique (same as activity-log-cache.test.js / editor-marker-contract):
|
|
// the route source is extracted from index.js via stable marker comments, the
|
|
// shaping block is wrapped into a real function and EXECUTED against fixture
|
|
// entries, plus source pins so the wiring can never silently drift.
|
|
|
|
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");
|
|
|
|
// Stable markers (the first is a comment this feature added to index.js; the
|
|
// others predate it and are pinned by activity-log-cache.test.js too).
|
|
const SHAPING_MARKER = "// --- Per-user filtering hook (response shaping)";
|
|
const ROUTE_START_MARKER =
|
|
'app.get("/api/server/:name/activity", rejectCrossSiteRead, activityLogRateLimiter';
|
|
const ROUTE_END_MARKER = 'app.post("/api/servers/statuses"';
|
|
|
|
function extractRegion(source, startMarker, endMarker, label, from = 0) {
|
|
const start = source.indexOf(startMarker, from);
|
|
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);
|
|
}
|
|
|
|
const routeRegion = extractRegion(indexSource, ROUTE_START_MARKER, ROUTE_END_MARKER, "index.js activity route");
|
|
|
|
// The shaping block: from the hook marker to the route's catch clause. As a
|
|
// function body it references exactly these bindings, so they become the
|
|
// wrapper's parameters and the block is exercised for real.
|
|
const shapingBlock = extractRegion(indexSource, SHAPING_MARKER, " } catch (err) {", "index.js shaping hook");
|
|
const runShapingSource = `(function (entries, offset, limit, canViewConsoleCommands, res) {\n${shapingBlock}\n})`;
|
|
|
|
const sandbox = {};
|
|
vm.createContext(sandbox);
|
|
// The shaping block now also masks entry.user through the SHARED
|
|
// maskPlannerEmailToLocalPart helper; slice the real helper into the sandbox
|
|
// so the shaper runs against shipped code (same technique as the mint-gates
|
|
// token-helper sandbox).
|
|
const maskHelperSource = indexSource.slice(
|
|
indexSource.indexOf("function maskPlannerEmailToLocalPart(value) {"),
|
|
indexSource.indexOf("async function fetchPlannerItemsForServer(")
|
|
);
|
|
assert.ok(maskHelperSource.includes("split('@')"), "mask helper region not sliced from index.js");
|
|
vm.runInContext(maskHelperSource, sandbox);
|
|
const runShaping = vm.runInContext(runShapingSource, sandbox);
|
|
|
|
function runShaper(entries, offset, limit, canViewConsoleCommands) {
|
|
const captured = {};
|
|
const res = { json: (payload) => { captured.payload = payload; } };
|
|
runShaping(entries, offset, limit, canViewConsoleCommands, res);
|
|
return captured.payload;
|
|
}
|
|
|
|
function fixtureEntries() {
|
|
return [
|
|
{ ts: 1, action: "server_start", details: { by: "admin" }, user: "admin@x", ip: "10.0.0.1" },
|
|
{ ts: 2, action: "console_command", details: { command: "register Admin hunter2" }, user: "admin@x", ip: "10.0.0.1" },
|
|
{ ts: 3, action: "console_command", details: { command: "backup now", source: "scheduler" }, user: "scheduler", ip: "scheduler" },
|
|
{
|
|
ts: 4,
|
|
action: "file_upload_url",
|
|
details: { path: "/srv/mod.zip", url: "https://cdn.example.com/mod.zip?X-Amz-Signature=SECRET&token=SECRET2", filename: "mod.zip", size: 10 },
|
|
user: "user@x",
|
|
ip: "10.0.0.2"
|
|
},
|
|
{ ts: 5, action: "console_command", details: { command: "op Admin" }, user: "admin@x", ip: "10.0.0.1" },
|
|
{ ts: 6, action: "file_create", details: { path: "/srv/a.txt" }, user: "user@x", ip: "10.0.0.2" },
|
|
{ ts: 7, action: "server_stop", details: null, user: "admin@x", ip: "10.0.0.1" }
|
|
];
|
|
}
|
|
|
|
// --- 1. console-command gating (behavioral, really executed) ---
|
|
|
|
test("strips every console_command entry for viewers without console_read (scheduler-sent included)", () => {
|
|
const entries = fixtureEntries();
|
|
const payload = runShaper(entries, 0, 200, false);
|
|
|
|
assert.ok(payload.ok);
|
|
for (const entry of payload.entries) {
|
|
assert.notEqual(entry.action, "console_command", "no console_command may reach a non-console_read viewer");
|
|
}
|
|
// 3 of 7 fixtures are console_command (one of them scheduler-sent — same class).
|
|
assert.equal(payload.total, 4);
|
|
assert.deepEqual(
|
|
payload.entries.map((e) => e.action),
|
|
["server_start", "file_upload_url", "file_create", "server_stop"]
|
|
);
|
|
});
|
|
|
|
test("admins and console_read holders keep the full trail including console_command", () => {
|
|
const entries = fixtureEntries();
|
|
const payload = runShaper(entries, 0, 200, true);
|
|
|
|
assert.equal(payload.total, 7);
|
|
assert.equal(payload.entries.filter((e) => e.action === "console_command").length, 3);
|
|
assert.deepEqual(
|
|
payload.entries.map((e) => e.ts),
|
|
entries.map((e) => e.ts),
|
|
"order and membership are untouched for permitted viewers"
|
|
);
|
|
});
|
|
|
|
test("gating hides console commands at EVERY offset: paging cannot surface them", () => {
|
|
const entries = fixtureEntries();
|
|
// Walk the whole filtered view in pages of 2 for a non-console_read viewer.
|
|
const seen = [];
|
|
let offset = 0;
|
|
let total = null;
|
|
while (true) {
|
|
const payload = runShaper(entries, offset, 2, false);
|
|
total = payload.total;
|
|
seen.push(...payload.entries);
|
|
if (offset >= payload.total) break;
|
|
offset += 2;
|
|
}
|
|
assert.equal(total, 4);
|
|
assert.equal(seen.filter((e) => e.action === "console_command").length, 0,
|
|
"no offset may point into hidden console_command entries");
|
|
});
|
|
|
|
// --- 2. URL query redaction (behavioral) ---
|
|
|
|
test("redacts the query string of details.url for EVERY viewer, admins included", () => {
|
|
for (const canViewConsoleCommands of [true, false]) {
|
|
const entries = fixtureEntries();
|
|
const payload = runShaper(entries, 0, 200, canViewConsoleCommands);
|
|
const upload = payload.entries.find((e) => e.action === "file_upload_url");
|
|
assert.equal(upload.details.url, "https://cdn.example.com/mod.zip",
|
|
`viewer (console=${canViewConsoleCommands}) must not see the credential query`);
|
|
assert.ok(!upload.details.url.includes("?"), "no '?' may survive redaction");
|
|
assert.equal(upload.details.path, "/srv/mod.zip", "non-url details survive redaction");
|
|
}
|
|
});
|
|
|
|
test("redaction only strips from the '?': plain URLs pass through by reference", () => {
|
|
const entries = [
|
|
{ ts: 1, action: "file_upload_url", details: { url: "https://cdn.example.com/no-query.bin" }, user: "u", ip: "i" },
|
|
{ ts: 2, action: "file_create", details: { path: "/a" }, user: "u", ip: "i" },
|
|
{ ts: 3, action: "server_stop", details: null, user: "u", ip: "i" },
|
|
{ ts: 4, action: "file_upload_url", details: { url: 12345 }, user: "u", ip: "i" }
|
|
];
|
|
const payload = runShaper(entries, 0, 200, true);
|
|
|
|
assert.strictEqual(payload.entries[0], entries[0],
|
|
"no '?' -> entry returned as-is (no copy, no rewrite)");
|
|
assert.equal(payload.entries[0].details.url, "https://cdn.example.com/no-query.bin");
|
|
assert.strictEqual(payload.entries[1], entries[1], "details without url untouched");
|
|
assert.strictEqual(payload.entries[2], entries[2], "null details untouched");
|
|
assert.strictEqual(payload.entries[3], entries[3], "non-string url untouched");
|
|
});
|
|
|
|
// --- 2b. details identity masking (behavioral) ---
|
|
|
|
test("details values that ARE emails are masked to the local part; free text is never mangled", () => {
|
|
const entries = [
|
|
{ ts: 1, action: "perms_change", details: { target: "owner@example.com", role: "console_read" }, user: "admin@x", ip: "i" },
|
|
{ ts: 2, action: "console_command", details: { command: "mail me at owner@example.com now" }, user: "u", ip: "i" },
|
|
{ ts: 3, action: "server_stop", details: null, user: "u", ip: "i" }
|
|
];
|
|
const snapshot = JSON.stringify(entries);
|
|
const payload = runShaper(entries, 0, 200, true);
|
|
|
|
const permsEntry = payload.entries.find((e) => e.action === "perms_change");
|
|
assert.equal(permsEntry.details.target, "owner",
|
|
"full email in details.target must reach the viewer as the local part only");
|
|
assert.equal(permsEntry.details.role, "console_read", "non-email details values survive untouched");
|
|
assert.equal(permsEntry.user, "admin", "user is masked alongside details");
|
|
|
|
const cmdEntry = payload.entries.find((e) => e.action === "console_command");
|
|
assert.equal(cmdEntry.details.command, "mail me at owner@example.com now",
|
|
"free text containing an email is NOT rewritten (the match is anchored on whole values)");
|
|
|
|
assert.strictEqual(payload.entries[2], entries[2], "null-details entry keeps reference identity");
|
|
assert.equal(JSON.stringify(entries), snapshot, "shaping must not mutate the cached records");
|
|
assert.equal(entries[0].details.target, "owner@example.com",
|
|
"masking is response-shaping: the cached record keeps the raw email");
|
|
});
|
|
|
|
// --- 3. cache must never be mutated (behavioral + structural) ---
|
|
|
|
test("the cached array and its entries are never mutated; redaction shallow-copies", () => {
|
|
const entries = fixtureEntries();
|
|
const snapshot = JSON.stringify(entries);
|
|
const uploadEntry = entries[3];
|
|
const uploadDetails = uploadEntry.details;
|
|
|
|
const payload = runShaper(entries, 0, 200, false);
|
|
|
|
assert.equal(JSON.stringify(entries), snapshot,
|
|
"input (cached) array must be byte-identical after shaping");
|
|
assert.equal(entries.length, 7, "cached array length unchanged");
|
|
assert.ok(entries.some((e) => e.action === "console_command"),
|
|
"console_command entries stay in the cache for permitted viewers");
|
|
assert.strictEqual(uploadEntry.details, uploadDetails, "original details object untouched");
|
|
assert.ok(uploadDetails.url.includes("?X-Amz-Signature=SECRET"), "original url keeps its query");
|
|
|
|
const redacted = payload.entries.find((e) => e.action === "file_upload_url");
|
|
assert.notStrictEqual(redacted, uploadEntry, "redacted entry is a shallow COPY, not the cached object");
|
|
assert.notStrictEqual(redacted.details, uploadDetails, "redacted details is a copy too");
|
|
|
|
// Masking (step 3) shallow-copies every entry whose user carries a full
|
|
// email — same discipline as redaction — while entries the shaper leaves
|
|
// untouched keep reference identity: under the admin view the
|
|
// scheduler-actor console_command entry passes through maskPlannerEmailToLocalPart
|
|
// unchanged ("scheduler" has no '@'), so it must be the SAME object.
|
|
const masked = payload.entries.find((e) => e.action === "server_start");
|
|
assert.notStrictEqual(masked, entries[0], "masked-user entries are shallow copies too");
|
|
assert.equal(masked.user, "admin", "response user is the local part only, never the full email");
|
|
assert.equal(entries[0].user, "admin@x", "masking is response-shaping: the cached record keeps the raw value");
|
|
|
|
const adminPayload = runShaper(entries, 0, 200, true);
|
|
const kept = adminPayload.entries.find((e) => e.ts === 3);
|
|
assert.strictEqual(kept, entries[2], "entries needing no change keep reference identity (no wholesale cloning)");
|
|
});
|
|
|
|
// --- 4. pagination/total are computed on the FILTERED array ---
|
|
|
|
test("pagination window and total come from the filtered view, not the raw entries", () => {
|
|
const entries = fixtureEntries();
|
|
// Filtered view = [server_start, file_upload_url, file_create, server_stop];
|
|
// page 2 of size 2 must be [file_create, server_stop] even though raw offset
|
|
// 2 sits on a hidden console_command.
|
|
const payload = runShaper(entries, 2, 2, false);
|
|
assert.deepEqual(payload.entries.map((e) => e.action), ["file_create", "server_stop"]);
|
|
assert.equal(payload.total, 4, "total counts only what this viewer may see");
|
|
assert.equal(payload.entries.length, 2, "response entries = the filtered page");
|
|
|
|
const adminPage = runShaper(entries, 5, 2, true);
|
|
assert.equal(adminPage.total, 7, "admin total reflects the unfiltered trail");
|
|
assert.deepEqual(adminPage.entries.map((e) => e.ts), [6, 7], "admin window walks the full array");
|
|
});
|
|
|
|
// --- 5. source pins: the route wiring cannot drift ---
|
|
|
|
test("gating flag derives from perms.console_read; admins skip the perms query", () => {
|
|
assert.ok(
|
|
routeRegion.includes("const canViewConsoleCommands = isAdminUser ? true : !!(perms && perms.console_read);"),
|
|
"canViewConsoleCommands must be true only for admins or console_read holders"
|
|
);
|
|
assert.ok(routeRegion.includes("let perms = null;"), "perms must be hoisted for the gating flag");
|
|
assert.doesNotMatch(routeRegion, /const perms = await getEffectivePermsForUserOnServer/,
|
|
"the perms lookup must stay on the non-admin path only (admins skip it)");
|
|
|
|
const nonAdminBlock = routeRegion.indexOf("if (!isAdminUser) {");
|
|
const permsLookup = routeRegion.indexOf("perms = await getEffectivePermsForUserOnServer");
|
|
const activity403 = routeRegion.indexOf("!perms || !perms.activity_logs");
|
|
const gatingFlag = routeRegion.indexOf("const canViewConsoleCommands");
|
|
assert.ok(nonAdminBlock >= 0 && nonAdminBlock < permsLookup,
|
|
"perms lookup stays inside the non-admin branch");
|
|
assert.ok(activity403 > permsLookup && gatingFlag > activity403,
|
|
"gating decision is computed only AFTER the activity_logs 403 (perms is guaranteed non-null there)");
|
|
});
|
|
|
|
test("gating and redaction sit AFTER cache retrieval and BEFORE pagination on the filtered array", () => {
|
|
const cacheGet = routeRegion.indexOf("activityLogEntryCache.get(serverName, st.mtimeMs, st.size)");
|
|
const shaping = routeRegion.indexOf(SHAPING_MARKER);
|
|
const filterAt = routeRegion.indexOf("entries.filter((entry) => !(entry && entry.action === \"console_command\"))");
|
|
const redactAt = routeRegion.indexOf("filtered.map((entry) => {");
|
|
const paginated = routeRegion.indexOf("const paginated = filtered.slice(offset, offset + limit);");
|
|
const total = routeRegion.indexOf("total: filtered.length,");
|
|
|
|
for (const [label, at] of [["shaping hook", shaping], ["gating filter", filterAt], ["redaction", redactAt], ["pagination", paginated]]) {
|
|
assert.ok(at > cacheGet, `${label} must run AFTER cache retrieval`);
|
|
}
|
|
assert.ok(filterAt < redactAt, "gating filter runs first, then URL redaction");
|
|
assert.ok(redactAt < paginated, "pagination slices the fully shaped array");
|
|
|
|
assert.ok(total > 0, "total must be filtered.length, not entries.length");
|
|
assert.ok(!routeRegion.includes("const paginated = entries.slice(offset, offset + limit);"),
|
|
"the old unfiltered pagination must be gone");
|
|
assert.ok(!routeRegion.includes("total: entries.length"),
|
|
"the old unfiltered total must be gone");
|
|
});
|
|
|
|
test("shaping builds new arrays and never mutates the shared cached data in place", () => {
|
|
assert.ok(routeRegion.includes("let filtered = canViewConsoleCommands"),
|
|
"filtering produces a NEW array binding; the cached `entries` is never reassigned-into");
|
|
assert.ok(shapingBlock.includes("{ ...entry, details: { ...details, url: url.split(\"?\")[0] } }"),
|
|
"redacted entries are shallow copies (entry AND details object)");
|
|
assert.doesNotMatch(shapingBlock, /\.(push|splice|sort|reverse|pop|shift|unshift)\(/,
|
|
"no in-place array mutation anywhere in the shaping hook");
|
|
assert.doesNotMatch(shapingBlock, /entries\.length\s*=/, "cached array length must never be rewritten");
|
|
});
|