Files
Kelx/tests/dashboard-assistant-delete-flow.test.js
2026-11-30 16:32:37 +00:00

450 lines
17 KiB
JavaScript

"use strict";
// Behavioral (runtime) tests for the dashboard assistant delete gate.
//
// tests/dashboard-assistant-delete-gate.test.js pins the gate stack statically;
// this file boots the real router with contract-compatible mocks and drives
// HTTP requests through it to pin the SEMANTICS:
// - an old/cached client (no intentId) and junk intentIds fail closed;
// - minted intents are bound to intentId+chatId+server and the confirm body
// must match the session intent BEFORE any single-use artifact burns;
// - a mismatched body costs neither the token nonce nor the intent;
// - the step-up challenge (403) carries revokeSecurity AND a re-minted
// pending intent so a mistyped credential is retryable;
// - a successful confirm deletes exactly the bound server, writes the full
// audit pair (per-server + _system with deletedBy/via/stepUp), flushes the
// index and status caches, and reports the grace window;
// - single-use holds: a consumed intent/token pair cannot be replayed.
const test = require("node:test");
const assert = require("node:assert");
const express = require("express");
const crypto = require("node:crypto");
const createDashboardAssistantRouter = require("../routes/dashboard-assistant.js");
const TEST_SECRET = "dashboard-assistant-delete-flow-test-secret";
const ADMIN_EMAIL = "admin@test.local";
function signPayload(payloadB64) {
return crypto.createHmac("sha256", TEST_SECRET).update(payloadB64).digest("base64url");
}
// Contract-compatible stand-ins for index.js's action-token machinery: signed,
// session-bound (uid+sid), action- and resource-bound, TTL'd, one-time via a
// session-tracked nonce.
function makeActionTokenDeps() {
function issueActionToken(req, action, resource = {}, opts = {}) {
const payload = {
v: 1,
uid: String(req.session.user || ""),
sid: String(req.sessionID || ""),
act: String(action),
res: JSON.stringify(resource || {}),
exp: Date.now() + Number(opts.ttlSeconds ?? 600) * 1000,
n: opts.oneTime ? crypto.randomBytes(16).toString("hex") : undefined,
};
const payloadB64 = Buffer.from(JSON.stringify(payload)).toString("base64url");
return `${payloadB64}.${signPayload(payloadB64)}`;
}
function requireActionTokenOr403(req, res, action, resource = {}) {
const token = req.get("x-action-token") || req.body?.actionToken || null;
let ok = false;
try {
const parts = String(token || "").split(".");
if (parts.length === 2 && signPayload(parts[0]) === parts[1]) {
const payload = JSON.parse(Buffer.from(parts[0], "base64url").toString("utf8"));
ok = payload.v === 1
&& payload.act === action
&& String(payload.uid).toLowerCase() === String(req.session.user).toLowerCase()
&& payload.sid === req.sessionID
&& payload.res === JSON.stringify(resource || {})
&& Number(payload.exp) > Date.now();
if (ok && payload.n) {
if (!req.session.usedActionNonces) req.session.usedActionNonces = {};
if (req.session.usedActionNonces[payload.n]) ok = false;
else req.session.usedActionNonces[payload.n] = payload.exp;
}
}
} catch {
ok = false;
}
if (!ok) {
res.status(403).json({ error: "invalid or missing action token" });
return false;
}
return true;
}
return { issueActionToken, requireActionTokenOr403 };
}
function bootApp({ admin = true } = {}) {
const session = {
user: ADMIN_EMAIL,
sessionIDPlaceholder: true,
usedActionNonces: {},
assistantDeleteIntents: {},
};
const calls = {
deletedServers: [],
activities: [],
indexCacheInvalidations: 0,
statusCacheDeletions: [],
};
const tokenDeps = makeActionTokenDeps();
const deps = {
// Auth layer
isAuthenticated: async () => !!session.user,
isAdmin: async () => admin,
findUserByEmail: async (email) => ({
id: 7,
email: String(email || "").toLowerCase(),
admin,
password: "$2b$12$mockhashformockingonlyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
}),
getDashboardAssistantConfig: () => ({ allowNormalUsers: false }),
// Action token machinery (contract-compatible mock)
issueActionToken: tokenDeps.issueActionToken,
requireActionTokenOr403: tokenDeps.requireActionTokenOr403,
// Step-up machinery: fresh password only; failure bodies carry
// revokeSecurity plus whatever failureResponseExtras() returns.
requireDestructiveActionStepUp: async (req, res, currentUser, subject, options = {}) => {
if (req.body?.currentPassword === "right-password") {
return { ok: true, graceExpiresAt: Date.now() + 5 * 60 * 1000, usedFreshVerification: true };
}
let extras = {};
if (typeof options.failureResponseExtras === "function") {
try {
extras = options.failureResponseExtras();
if (!extras || typeof extras !== "object") extras = {};
} catch {
extras = {};
}
}
res.status(403).json({
error: "Current password is required",
code: "password-required",
revokeSecurity: {
twoFactorEnabled: false,
authMethod: "password",
requiresVerification: true,
requiresTwoFactor: false,
graceExpiresAt: 0,
graceUsesRemaining: 0,
graceUsesLimit: 5,
},
...extras,
});
return { ok: false, handled: true };
},
getDestructiveActionSecurityAsync: async () => ({
twoFactorEnabled: false,
authMethod: "password",
requiresVerification: true,
requiresTwoFactor: false,
graceExpiresAt: 0,
graceUsesRemaining: 0,
graceUsesLimit: 5,
}),
getVerifiedSessionRevokeGraceState: async () => null,
// Rate limiters: pass-through (budgeting is pinned statically; not the
// semantics under test here).
sessionRevoke2faRateLimiter: (req, res, next) => next(),
dashboardAssistantDeleteIntentRateLimiter: (req, res, next) => next(),
getRequestIp: () => "203.0.113.7",
// Service layer doubles
db: require("./helpers/assistant-history-db").assistantHistoryDb(async () => []),
loadServersIndex: async () => [
{ name: "survival", displayName: "Survival" },
{ name: "creative", displayName: "Creative" },
],
deleteServerByName: async (name) => {
calls.deletedServers.push(name);
return { ok: true, deleting: false };
},
recordActivity: (target, action, details, actor, ip) => {
calls.activities.push({ target, action, details, actor, ip });
},
invalidateServerIndexCache: () => {
calls.indexCacheInvalidations += 1;
},
deleteStatusCacheEntry: (name) => {
calls.statusCacheDeletions.push(name);
},
};
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 post = async (path, body, headers = {}) =>
fetch(`${base}${path}`, {
method: "POST",
headers: { "Content-Type": "application/json", ...headers },
body: JSON.stringify(body),
});
const postRaw = async (path, contentType, body, headers = {}) =>
fetch(`${base}${path}`, {
method: "POST",
headers: { "Content-Type": contentType, ...headers },
body,
});
const close = () => new Promise((resolve) => server.close(resolve));
return { session, calls, post, postRaw, base, close };
}
async function mintIntent(post, server = "survival", chatId = 7) {
const response = await post("/delete-intent", { chatId, server });
assert.strictEqual(response.status, 200, "intent mint should succeed");
const data = await response.json();
assert.ok(data?.ok && data.intent?.intentId && data.intent?.actionToken, "intent payload is complete");
return data.intent;
}
test("delete-intent rejects non-admin sessions and mints a bound, one-time intent for admins", async () => {
const nonAdmin = bootApp({ admin: false });
try {
const denied = await nonAdmin.post("/delete-intent", { chatId: 7, server: "survival" });
assert.strictEqual(denied.status, 403, "non-admins cannot mint delete intents");
} finally {
await nonAdmin.close();
}
const env = bootApp({ admin: true });
try {
const intent = await mintIntent(env.post);
assert.strictEqual(intent.server.name, "survival");
assert.strictEqual(intent.server.displayName, "Survival");
assert.strictEqual(intent.chatId, 7);
const stored = env.session.assistantDeleteIntents[intent.intentId];
assert.ok(stored, "pending intent is registered in the session");
assert.strictEqual(stored.serverName, "survival");
assert.ok(Number(stored.expiresAt) > Date.now(), "intent carries a live expiry");
const unknown = await env.post("/delete-intent", { chatId: 7, server: "does-not-exist" });
assert.strictEqual(unknown.status, 404, "unknown servers cannot mint intents");
} finally {
await env.close();
}
});
test("confirm-delete fails closed for old clients and junk intentIds", async () => {
const env = bootApp();
try {
// Old cached client: no intentId at all.
const legacy = await env.post("/confirm-delete", { chatId: 7, server: "survival" });
assert.strictEqual(legacy.status, 403);
assert.strictEqual((await legacy.json()).code, "intent-invalid");
const junk = await env.post("/confirm-delete", {
chatId: 7,
server: "survival",
intentId: "../etc/passwd",
});
assert.strictEqual(junk.status, 403);
assert.strictEqual((await junk.json()).code, "intent-invalid");
assert.ok(
!Object.keys(env.session.assistantDeleteIntents).length,
"no artifacts were minted or consumed by the rejected requests"
);
} finally {
await env.close();
}
});
test("both gated endpoints enforce a JSON body (415)", async () => {
const env = bootApp();
try {
const formConfirm = await env.postRaw(
"/confirm-delete",
"application/x-www-form-urlencoded",
"server=survival"
);
assert.strictEqual(formConfirm.status, 415, "confirm-delete rejects non-JSON bodies");
const formIntent = await env.postRaw(
"/delete-intent",
"application/x-www-form-urlencoded",
"server=survival"
);
assert.strictEqual(formIntent.status, 415, "delete-intent rejects non-JSON bodies");
} finally {
await env.close();
}
});
test("a mismatched confirm body costs neither the token nonce nor the intent", async () => {
const env = bootApp();
try {
const intent = await mintIntent(env.post);
const wrongServer = await env.post("/confirm-delete", {
chatId: 7,
server: "creative",
intentId: intent.intentId,
}, { "x-action-token": intent.actionToken });
assert.strictEqual(wrongServer.status, 400);
assert.strictEqual((await wrongServer.json()).code, "intent-mismatch");
assert.ok(env.session.assistantDeleteIntents[intent.intentId], "intent survives a mismatched body");
assert.ok(!Object.keys(env.session.usedActionNonces || {}).length, "nonce is NOT burned on a mismatched body");
const wrongChat = await env.post("/confirm-delete", {
chatId: 8,
server: "survival",
intentId: intent.intentId,
}, { "x-action-token": intent.actionToken });
assert.strictEqual(wrongChat.status, 400);
// The same intent + token still completes the flow afterwards.
const success = await env.post("/confirm-delete", {
chatId: 7,
server: "survival",
intentId: intent.intentId,
currentPassword: "right-password",
}, { "x-action-token": intent.actionToken });
assert.strictEqual(success.status, 200);
} finally {
await env.close();
}
});
test("step-up challenge returns revokeSecurity plus a re-minted intent, and the retry completes", async () => {
const env = bootApp();
try {
const intent = await mintIntent(env.post);
const challenge = await env.post("/confirm-delete", {
chatId: 7,
server: "survival",
intentId: intent.intentId,
}, { "x-action-token": intent.actionToken });
assert.strictEqual(challenge.status, 403);
const body = await challenge.json();
assert.strictEqual(body.code, "password-required");
assert.ok(body.revokeSecurity?.requiresVerification, "challenge carries the security state");
// The consumed intent is gone; the failure body carries a fresh one that
// is registered in the session and usable for the retry.
assert.ok(!env.session.assistantDeleteIntents[intent.intentId], "consumed intent is removed");
assert.ok(body.intent?.intentId && body.intent.intentId !== intent.intentId, "a fresh intent is returned");
assert.ok(env.session.assistantDeleteIntents[body.intent.intentId], "fresh intent is registered in the session");
assert.strictEqual(body.intent.server.name, "survival", "re-mint stays bound to the same server");
assert.strictEqual(body.intent.chatId, 7, "re-mint stays bound to the same chat");
const retry = await env.post("/confirm-delete", {
chatId: 7,
server: "survival",
intentId: body.intent.intentId,
currentPassword: "right-password",
}, { "x-action-token": body.intent.actionToken });
assert.strictEqual(retry.status, 200);
assert.deepStrictEqual(env.calls.deletedServers, ["survival"]);
} finally {
await env.close();
}
});
test("a successful confirm writes full audit parity and flushes both caches", async () => {
const env = bootApp();
try {
const intent = await mintIntent(env.post);
const response = await env.post("/confirm-delete", {
chatId: 7,
server: "survival",
intentId: intent.intentId,
currentPassword: "right-password",
}, { "x-action-token": intent.actionToken });
assert.strictEqual(response.status, 200);
const data = await response.json();
assert.ok(data.ok && data.reply === "Deleted survival.", "assistant reply confirms the delete");
assert.ok(Number(data.graceExpiresAt) > Date.now(), "grace window is reported");
assert.deepStrictEqual(env.calls.deletedServers, ["survival"]);
assert.strictEqual(env.calls.indexCacheInvalidations, 1);
assert.deepStrictEqual(env.calls.statusCacheDeletions, ["survival"]);
assert.strictEqual(env.calls.activities.length, 2, "per-server + _system audit records");
const perServer = env.calls.activities.find((a) => a.target === "survival");
const system = env.calls.activities.find((a) => a.target === "_system");
assert.ok(perServer && system, "both audit targets present");
for (const record of [perServer, system]) {
assert.strictEqual(record.action, "server_delete");
assert.strictEqual(record.details.deletedBy, ADMIN_EMAIL);
assert.strictEqual(record.details.via, "dashboard-assistant");
assert.strictEqual(record.details.stepUp, "fresh-credential");
assert.strictEqual(record.actor, ADMIN_EMAIL);
assert.strictEqual(record.ip, "203.0.113.7", "trusted-proxy IP resolver output is audited");
}
assert.strictEqual(system.details.server, "survival");
} finally {
await env.close();
}
});
test("single-use holds: consumed intents cannot be replayed and bound tokens cannot cross intents", async () => {
const env = bootApp();
try {
const intent = await mintIntent(env.post);
const first = await env.post("/confirm-delete", {
chatId: 7,
server: "survival",
intentId: intent.intentId,
currentPassword: "right-password",
}, { "x-action-token": intent.actionToken });
assert.strictEqual(first.status, 200);
const replay = await env.post("/confirm-delete", {
chatId: 7,
server: "survival",
intentId: intent.intentId,
currentPassword: "right-password",
}, { "x-action-token": intent.actionToken });
assert.strictEqual(replay.status, 403, "consumed intent cannot be replayed");
// Token bound to intent B cannot confirm intent A: the resource check
// rejects it (and the nonce for B never burns for A's use).
const intentA = await mintIntent(env.post, "survival");
const intentB = await mintIntent(env.post, "creative");
const cross = await env.post("/confirm-delete", {
chatId: 7,
server: "survival",
intentId: intentA.intentId,
currentPassword: "right-password",
}, { "x-action-token": intentB.actionToken });
assert.strictEqual(cross.status, 403);
assert.strictEqual((await cross.json()).error, "invalid or missing action token");
// Expired session intents fail closed even with a fresh-looking request.
const expiredId = "a".repeat(32);
env.session.assistantDeleteIntents[expiredId] = {
chatId: 7,
serverName: "survival",
displayName: "Survival",
issuedAt: Date.now() - 60000,
expiresAt: Date.now() - 30000,
};
const expired = await env.post("/confirm-delete", {
chatId: 7,
server: "survival",
intentId: expiredId,
});
assert.strictEqual(expired.status, 403);
assert.strictEqual((await expired.json()).code, "intent-invalid");
assert.ok(!env.session.assistantDeleteIntents[expiredId], "expired intent is evicted");
} finally {
await env.close();
}
});