"use strict"; // Tests for the ADMIN SURFACING + HTTP classification of the legacy enc-v1 // provider-key condition (third leg of the enc-v1 remediation, alongside the // migration self-heal and the runtime fail-closed guard): // // - router: the fail-closed legacy guard's curated error ("legacy encryption // envelope") must classify as a curated 503 — operator-actionable, secret- // free, admin-gated — instead of the generic 500 fallback, while every // other message class keeps its pre-existing classification. The // classifier is module-internal to the router factory, so it is driven // through the real POST /chat route with a stubbed service (the router // destructures createDashboardAssistantService at require time, so the // stub is installed via a mutable delegate BEFORE the router module is // first loaded in this process). // - service: the admin bootstrap carries a secret-free `keyMigration` object // ({ legacyPending, retired, attempted, lastFailureReason, orphanedKeys }) // that mirrors the guard's live condition: attempted + unretired + a // stored enc-v1 envelope in the secret cache. orphanedKeys counts // providers whose ORPHANED_V1 quarantine slot holds a recovery artifact. // Normal users get no keyMigration at all. // // This file runs in its own process, so the module-wide retirement flag starts // false. Order matters (same discipline as the legacy-guard test file): the // boot-window and unretired scenarios come first and the ONE // retirement-confirming test comes LAST — the flag is one-way per process. const test = require("node:test"); const assert = require("node:assert"); const crypto = require("crypto"); const express = require("express"); // Patching order is load-bearing: the router destructures the service factory // at require time, so the delegate must be installed before the router module // is first loaded. With no stub installed the delegate is the real factory. const serviceModule = require("../utils/dashboard-assistant-service.js"); const realCreateDashboardAssistantService = serviceModule.createDashboardAssistantService; let routerServiceStub = null; serviceModule.createDashboardAssistantService = (deps) => (routerServiceStub ? routerServiceStub : realCreateDashboardAssistantService(deps)); const createDashboardAssistantRouter = require("../routes/dashboard-assistant.js"); const { encryptAssistantProviderToken, getAssistantProviderSecretMigrationState, } = serviceModule; const ADMIN_EMAIL = "admin@test.local"; // Distinctive secret strings for the secret-free payload/log assertions. const DEDICATED_SECRET = "dedicated-secret-surfacing-suite-DO-NOT-LOG"; const GROQ_PLAINTEXT = "gsk-PLAINTEXT-SURFACING-SUITE-DO-NOT-LOG"; const TEST_SECRETS = [DEDICATED_SECRET, GROQ_PLAINTEXT]; function assertNoSecrets(text) { for (const secret of TEST_SECRETS) { assert.ok(!text.includes(secret), `output must never contain the test secret ${JSON.stringify(secret)}`); } } // Mirrors the legacy enc-v1 scheme: unsalted SHA-256 over context\0secret // (same construction the legacy-guard test file uses against the real KDF). const CONTEXT = "adpanel:dashboard-assistant:provider-key:v1"; function legacyEncryptV1(token, secret) { const key = crypto .createHash("sha256") .update(CONTEXT) .update("\0") .update(secret) .digest(); const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv("aes-256-gcm", key, iv); const ciphertext = Buffer.concat([cipher.update(token, "utf8"), cipher.final()]); return [ "enc-v1", iv.toString("base64"), cipher.getAuthTag().toString("base64"), ciphertext.toString("base64"), ].join(":"); } const SECRET_ENV_KEYS = [ "DASHBOARD_ASSISTANT_ENCRYPTION_SECRET", "SESSION_SECRET", "SECRET_KEY", ]; const PROVIDER_ENCRYPTED_ENV_KEYS = [ "DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED", "DASHBOARD_ASSISTANT_GOOGLE_AI_API_KEY_ENCRYPTED", ]; const OTHER_ENV_KEYS = [ "DASHBOARD_ASSISTANT_PROVIDER", "GROQ_API_KEY", "GOOGLE_AI_STUDIO_API_KEY", "GOOGLE_AI_KEY", "DASHBOARD_ASSISTANT_GROQ_MODEL", "DASHBOARD_ASSISTANT_GOOGLE_MODEL", ]; // Async-aware env guard: the scheduled migration runs from setImmediate while // the test body awaits, so the overrides must hold until fn settles. async function withSurfacingEnv(overrides, fn) { const keys = [...SECRET_ENV_KEYS, ...PROVIDER_ENCRYPTED_ENV_KEYS, ...OTHER_ENV_KEYS]; const saved = new Map(keys.map((key) => [key, process.env[key]])); try { for (const key of keys) delete process.env[key]; for (const [key, value] of Object.entries(overrides)) { process.env[key] = value; } return await fn(); } finally { for (const key of keys) { const previous = saved.get(key); if (previous === undefined) delete process.env[key]; else process.env[key] = previous; } } } // In-memory stand-in for .env plus every dep getBootstrap needs: the secret // cache/migration deps (readEnvFile / writeEnvFileBatch / getEnvFileMtimeMs) // and the bootstrap deps (findUserByEmail / getDashboardAssistantConfig / db). // failWrites makes the first N batch writes report failure (simulated // read-only .env) so a migration ATTEMPTS but does not RETIRE. The model // override env keeps getBootstrap off the live model-list HTTP call entirely. function createSurfacingDeps(initialEnv, { failWrites = 0, admin = true } = {}) { const env = { ...initialEnv }; const writes = []; const state = { pendingFailures: failWrites }; let mtime = 1_000; const deps = { readEnvFile: () => ({ ...env }), writeEnvFileBatch: (updates) => { if (state.pendingFailures > 0) { state.pendingFailures -= 1; return false; } writes.push(updates); for (const [key, value] of Object.entries(updates)) { if (value === null) delete env[key]; else env[key] = value; } mtime += 1; return true; }, getEnvFileMtimeMs: () => mtime, findUserByEmail: async (email) => ({ id: 7, email: String(email || "").toLowerCase(), admin }), getDashboardAssistantConfig: () => ({ allowNormalUsers: true }), db: require("./helpers/assistant-history-db").assistantHistoryDb(fakeDbQuery), }; return { env, writes, deps, allowWrites: () => { state.pendingFailures = 0; }, bumpMtime: () => { mtime += 1; }, }; } // Minimal DB stand-in for the bootstrap chat queries (same shape the // model-selection test file uses to drive getBootstrap). function fakeDbQuery(sql) { const s = String(sql); const CHAT_ROW = { id: 7, title: "chat", created_at: 0, updated_at: 0 }; if (s.includes("CREATE TABLE")) return Promise.resolve([]); if (s.includes("WHERE id = ? AND user_email = ?")) return Promise.resolve([CHAT_ROW]); if (s.includes("SELECT COUNT(*)")) return Promise.resolve([{ total: 0 }]); if (s.includes("SELECT title FROM dashboard_assistant_chats")) { return Promise.resolve([{ title: "chat" }]); } if (s.includes("user_email = ?")) return Promise.resolve([CHAT_ROW]); if (s.includes("WHERE id = ? LIMIT 1")) return Promise.resolve([CHAT_ROW]); return Promise.resolve([]); } // Resolves after the service's scheduled first-attempt setImmediate has run // (queued before this promise's callback, so ordering is guaranteed). function afterImmediate() { return new Promise((resolve) => setImmediate(resolve)); } // Captures console output so failing migrations and the classifier's 500 log // never leak into the runner output. async function captureConsoleAsync(fn) { const lines = { error: [], warn: [], log: [] }; const originals = { error: console.error, warn: console.warn, log: console.log }; for (const level of Object.keys(originals)) { console[level] = (...args) => lines[level].push(args.map(String).join(" ")); } try { return { result: await fn(), lines }; } finally { console.error = originals.error; console.warn = originals.warn; console.log = originals.log; } } // Mounts the real router against a stub service whose completeChat throws // whatever getError() returns — the classifier under test sits in the real // respondWithError path behind POST /chat. function bootThrowingChatApp(getError) { routerServiceStub = { completeChat: async () => { throw getError(); }, }; const session = { user: ADMIN_EMAIL }; const deps = { isAuthenticated: async () => true, isAdmin: async () => true, findUserByEmail: async (email) => ({ id: 7, email: String(email || "").toLowerCase(), admin: true }), getDashboardAssistantConfig: () => ({ allowNormalUsers: true }), db: require("./helpers/assistant-history-db").assistantHistoryDb(fakeDbQuery), }; const app = express(); app.use(express.json()); app.use((req, res, next) => { req.session = session; req.sessionID = "surfacing-test-sid"; 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 postChat = async () => fetch(`${base}/chat`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ chatId: 7, message: "hi" }), }); const close = () => new Promise((resolve) => server.close(resolve)); return { postChat, close }; } // The guard's canonical rejection text as the service throws it (provider // label + why-sentence + both remediations; the "legacy encryption envelope" // marker is the load-bearing classifier contract). Two-file contract: the // real thrown message is pinned by utils/dashboard-assistant-service-legacy-guard.test.js // (assertGuardErrorMessage), so marker drift is caught there — this constant // only needs to stay faithful to what that file pins. const GUARD_ERROR_MESSAGE = "The stored Groq API key still uses the legacy encryption envelope and its automatic re-encryption has not completed. " + "The legacy envelope relies on a weak legacy key derivation, so the key stays exposed until it is re-encrypted. " + "Re-save the provider key in the assistant settings to migrate it, or restore .env write access and restart the panel."; test("POST /chat classifies the legacy-envelope guard error as a curated, admin-actionable 503", async () => { const env = bootThrowingChatApp(() => new Error(GUARD_ERROR_MESSAGE)); try { const res = await env.postChat(); assert.strictEqual(res.status, 503, "the guard condition is operator-fixable, not an internal fault"); const body = await res.json(); assert.strictEqual(body.error, GUARD_ERROR_MESSAGE, "the full curated message (remediation included) reaches the admin client"); assert.ok(!body.error.includes(GROQ_PLAINTEXT) && !body.error.includes(DEDICATED_SECRET)); } finally { await env.close(); routerServiceStub = null; } }); test("POST /chat still answers 500 with the generic fallback for unexpected errors", async () => { const env = bootThrowingChatApp(() => new Error("connect ECONNREFUSED 10.0.0.12:3306")); try { const { result: res, lines } = await captureConsoleAsync(() => env.postChat()); assert.strictEqual(res.status, 500, "raw internal error text must never classify as a curated status"); const body = await res.json(); assert.strictEqual(body.error, "Assistant request failed.", "the generic fallback hides internal topology"); assert.strictEqual(lines.error.length, 1, "the fault is logged server-side exactly once"); } finally { await env.close(); routerServiceStub = null; } }); test("every pre-existing message class keeps its classification (order/behavior pin)", async () => { const cases = [ ["not authenticated", 401], ["admin required", 403], ["you lack permission for that action", 403], ["assistant access disabled", 403], ["provider rate limit hit", 429], ["quota exhausted for today", 429], // Classifier precedence (branch order matters): the 429 quota branch runs // BEFORE the curated 503 group, so a message carrying BOTH fragments must // classify as 429. The guard's real marker alone maps to 503 — pinned by // the dedicated test above, and asserted again by the sibling case below. ["quota exceeded while the legacy encryption envelope is pending", 429], [GUARD_ERROR_MESSAGE, 503], ["Groq is not configured.", 503], ["the chat tool limit was reached", 503], ["the provider returned an empty response", 503], // Pre-existing 503 member: the provider-key crypto fail-closed error, // quoted exactly as production throws it. ["Assistant encryption secret is unavailable.", 503], ["that chat could not be found", 404], ["the selected model was not found", 404], ["audio format is not supported", 415], ["a message is required", 400], ["the request is invalid", 400], ["the upload is too large", 400], ["your message is too long", 400], ["the audio could not be transcribed", 400], ["no audio was provided", 400], ]; let cursor = 0; const env = bootThrowingChatApp(() => new Error(cases[cursor][0])); try { const { result: results } = await captureConsoleAsync(async () => { const statuses = []; for (; cursor < cases.length; cursor += 1) { const res = await env.postChat(); statuses.push(res.status); await res.json(); } return statuses; }); assert.deepStrictEqual( results, cases.map(([, expected]) => expected), "each curated message class must keep its pre-existing status" ); } finally { await env.close(); routerServiceStub = null; } }); // --------------------------------------------------------------------------- // getBootstrap keyMigration — boot window first, unretired second, and the // retirement-confirming scenario LAST (the flag is one-way per process). // --------------------------------------------------------------------------- test("getBootstrap keyMigration in the boot window: no attempt yet, legacyPending false", async () => { await withSurfacingEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET, DASHBOARD_ASSISTANT_GROQ_MODEL: "pinned-override-model", }, async () => { const harness = createSurfacingDeps( { DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET) }, { failWrites: 1 } ); const { result: boot, lines } = await captureConsoleAsync(async () => { const service = realCreateDashboardAssistantService(harness.deps); // The bootstrap's awaits all resolve via microtasks, which drain before // the queued setImmediate migration attempt (check phase) can run — the // same boot window the legacy guard stays permissive in. const result = await service.getBootstrap({ session: { user: ADMIN_EMAIL } }); assert.strictEqual(getAssistantProviderSecretMigrationState().attempted, false, "the boot window holds: no attempt yet"); await afterImmediate(); // let the queued attempt land (fails: read-only .env) assert.strictEqual(getAssistantProviderSecretMigrationState().attempted, true); return result; }); assert.strictEqual(boot.canConfigure, true); assert.deepStrictEqual(boot.keyMigration, { legacyPending: false, retired: false, attempted: false, lastFailureReason: "", orphanedKeys: 0, }, "retirement is merely unconfirmed in the boot window, exactly like the guard"); for (const line of [...lines.error, ...lines.warn, ...lines.log]) assertNoSecrets(line); }); }); test("getBootstrap keyMigration while unretired: legacyPending true with the curated failure reason", async () => { await withSurfacingEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET, DASHBOARD_ASSISTANT_GROQ_MODEL: "pinned-override-model", }, async () => { // The migration's FIRST .env read throws (curated env-read-failed); every // later read serves the real env, so the secret cache still loads and the // stored provider value keeps its enc-v1 envelope. const envSnapshot = { DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET) }; let readEnvCalls = 0; const deps = { readEnvFile: () => { readEnvCalls += 1; if (readEnvCalls === 1) throw new Error("simulated unreadable .env"); return { ...envSnapshot }; }, writeEnvFileBatch: () => false, getEnvFileMtimeMs: () => 1_000, findUserByEmail: async (email) => ({ id: 7, email: String(email || "").toLowerCase(), admin: true }), getDashboardAssistantConfig: () => ({ allowNormalUsers: true }), db: require("./helpers/assistant-history-db").assistantHistoryDb(fakeDbQuery), }; const { result: boot, lines } = await captureConsoleAsync(async () => { const service = realCreateDashboardAssistantService(deps); await afterImmediate(); // the first migration attempt fires and fails the read const state = getAssistantProviderSecretMigrationState(); assert.strictEqual(state.attempted, true); assert.strictEqual(state.retired, false); assert.strictEqual(state.lastFailureReason, "env-read-failed"); return service.getBootstrap({ session: { user: ADMIN_EMAIL } }); }); assert.deepStrictEqual(boot.keyMigration, { legacyPending: true, retired: false, attempted: true, lastFailureReason: "env-read-failed", orphanedKeys: 0, }, "the live condition (attempted + unretired + stored enc-v1 envelope) is surfaced"); // Every keyMigration value is a secret-free primitive, and no key material // appears anywhere in the serialized admin payload. for (const [key, value] of Object.entries(boot.keyMigration)) { assert.ok(["boolean", "number", "string"].includes(typeof value), `keyMigration.${key} must be a primitive`); } assertNoSecrets(JSON.stringify(boot)); for (const line of [...lines.error, ...lines.warn, ...lines.log]) assertNoSecrets(line); }); }); test("getBootstrap keyMigration after retirement: retired true, legacyPending false, absent for normal users", async () => { await withSurfacingEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET, DASHBOARD_ASSISTANT_GROQ_MODEL: "pinned-override-model", }, async () => { // .env holds only an enc-v2 value (and nothing undecryptable): the boot // attempt confirms retirement without a write. This is the ONE // retirement-confirming test in this file — kept last on purpose. const harness = createSurfacingDeps( { DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: encryptAssistantProviderToken("already-migrated-groq-key") } ); const { result: boot, lines } = await captureConsoleAsync(async () => { const service = realCreateDashboardAssistantService(harness.deps); await afterImmediate(); assert.strictEqual(getAssistantProviderSecretMigrationState().retired, true); return service.getBootstrap({ session: { user: ADMIN_EMAIL } }); }); assert.deepStrictEqual(boot.keyMigration, { legacyPending: false, retired: true, attempted: true, lastFailureReason: "", orphanedKeys: 0, }, "a retired process reports success and clears the failure history"); assertNoSecrets(JSON.stringify(boot)); // Normal-user bootstrap keeps its exact pre-existing shape: no keyMigration // (no remediation power, no crypto-hygiene detail). const userHarness = createSurfacingDeps( { DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: encryptAssistantProviderToken("already-migrated-groq-key") }, { admin: false } ); const userService = realCreateDashboardAssistantService(userHarness.deps); const { result: userBoot } = await captureConsoleAsync(async () => { await afterImmediate(); return userService.getBootstrap({ session: { user: "user@test.local" } }); }); assert.strictEqual(userBoot.canConfigure, false); assert.strictEqual(userBoot.keyMigration, undefined, "normal users get no keyMigration at all"); assertNoSecrets(JSON.stringify(userBoot)); for (const line of [...lines.error, ...lines.warn, ...lines.log]) assertNoSecrets(line); }); }); // --------------------------------------------------------------------------- // LAST: the quarantine-slot surfacing case. It needs retired === true, so it // sits after the one retirement-confirming test above (the flag is one-way // per process) and performs no retirement flip of its own beyond the boot // run's re-confirmation. // --------------------------------------------------------------------------- test("getBootstrap keyMigration surfaces an occupied ORPHANED_V1 quarantine slot (orphanedKeys 1)", async () => { await withSurfacingEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET, DASHBOARD_ASSISTANT_GROQ_MODEL: "pinned-override-model", }, async () => { // The live config is enc-v1-free (the migration already quarantined the // undecryptable value in an earlier boot): .env holds ONLY the groq // recovery artifact. The boot run confirms retirement without a write — // nothing in .env is enc-v1 anymore — and the occupied slot must surface // as orphanedKeys: 1 with legacyPending false (nothing live blocks). const orphanedArtifact = legacyEncryptV1(GROQ_PLAINTEXT, "lost-secret"); const harness = createSurfacingDeps({ DASHBOARD_ASSISTANT_GROQ_API_KEY_ORPHANED_V1: orphanedArtifact, }); const { result: boot, lines } = await captureConsoleAsync(async () => { const service = realCreateDashboardAssistantService(harness.deps); await afterImmediate(); assert.strictEqual(getAssistantProviderSecretMigrationState().retired, true); return service.getBootstrap({ session: { user: ADMIN_EMAIL } }); }); assert.deepStrictEqual(boot.keyMigration, { legacyPending: false, retired: true, attempted: true, lastFailureReason: "", orphanedKeys: 1, }, "the occupied quarantine slot surfaces without reopening the legacy-pending condition"); // The boot run must not have touched .env (retirement re-confirmed via // the nothing-to-do path) and the artifact must survive byte-identical. assert.strictEqual(harness.writes.length, 0, "re-confirmation never writes .env"); assert.strictEqual(harness.env.DASHBOARD_ASSISTANT_GROQ_API_KEY_ORPHANED_V1, orphanedArtifact); assertNoSecrets(JSON.stringify(boot)); for (const line of [...lines.error, ...lines.warn, ...lines.log]) assertNoSecrets(line); }); });