"use strict"; // Tests for the RUNTIME FAIL-CLOSED GUARD: while the enc-v1 → enc-v2 // migration has been ATTEMPTED but retirement is UNCONFIRMED (the known-weak // state — provider keys still decrypt through the weak unsalted-SHA-256 // legacy chain whose candidate list includes SECRET_KEY, the reCAPTCHA secret // a third party holds by design), the chat-serving paths must refuse to // exercise a provider key that still wears an enc-v1 envelope instead of // silently sending it out. Boot window (pre-first-attempt) and // retirement-confirmed operation stay permissive; a re-saved (enc-v2) key // clears the condition for its provider. // // This file runs in its own process, so the module-wide retirement flag // starts false. Order matters and mirrors the discipline documented in the // encryption/migration-retry test files: the boot-window and guard-firing // (retired===false) 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 { encryptAssistantProviderToken, createDashboardAssistantService, getAssistantProviderSecretMigrationState, } = require("./dashboard-assistant-service"); 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", ]; const CONTEXT = "adpanel:dashboard-assistant:provider-key:v1"; // Distinctive secret strings for the secret-free message/log assertions. const DEDICATED_SECRET = "dedicated-secret-guard-suite-DO-NOT-LOG"; const GROQ_PLAINTEXT = "gsk-PLAINTEXT-GROQ-GUARD-SUITE-DO-NOT-LOG"; const GOOGLE_PLAINTEXT = "AIza-PLAINTEXT-GOOGLE-GUARD-SUITE-DO-NOT-LOG"; const TEST_SECRETS = [DEDICATED_SECRET, GROQ_PLAINTEXT, GOOGLE_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. 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(":"); } // 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 withGuardEnv(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 the deps the secret cache and the // scheduled migration need. failWrites makes the first N batch writes report // failure (simulated read-only .env) so the startup migration ATTEMPTS but // does not RETIRE — exactly the known-weak state the guard exists for. // getEnvFileMtimeMs models the atomic-rename mtime bump every write performs // (the cross-worker cache invalidation signal). function createGuardDeps(initialEnv, { failWrites = 0, withMtime = 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; }, }; if (withMtime) { deps.getEnvFileMtimeMs = () => mtime; } return { env, writes, deps, allowWrites: () => { state.pendingFailures = 0; }, bumpMtime: () => { mtime += 1; }, }; } // 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 (the failing migrations and the guard's rate- // limited console.error must never leak into the runner output) while the // async body runs. 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; } } // Awaits a promise expected to reject and hands back the error for // multi-part assertions. async function catchRejection(promise) { let caught = null; try { await promise; } catch (error) { caught = error; } assert.ok(caught, "expected the call to reject"); return caught; } // The guard's canonical rejection text: load-bearing marker + provider label // + one why-sentence + exactly the two practical remediations. function assertGuardErrorMessage(error, providerLabel) { assert.match(error.message, /legacy encryption envelope/, "the classifier marker must be present"); assert.ok(error.message.includes(providerLabel), `the message must name the provider label (${providerLabel})`); assert.ok( error.message.includes("still uses the legacy encryption envelope and its automatic re-encryption has not completed."), "the message must state the condition" ); assert.ok(error.message.includes("weak legacy key derivation"), "the message must carry the why-sentence"); assert.ok( error.message.includes("Re-save the provider key in the assistant settings to migrate it, or restore .env write access and restart the panel."), "the message must carry both remediations" ); assertNoSecrets(error.message); } // An empty buffer lands on the FIRST post-guard check of transcribeAudio: // rejecting with this exact message proves the guard did NOT fire and no // provider call was attempted. const NO_AUDIO_MESSAGE = "No audio data was received."; // Minimal DB stand-in for completeClientFollowUp's chat persistence (same // shape the legacy-key-surfacing test file uses to drive its bootstrap): // chat lookups resolve one live chat, message reads return no history, and // message inserts are recorded so the skipAi test can assert exactly what // was persisted. const FOLLOWUP_CHAT_ROW = { id: 7, title: "chat", created_at: 0, updated_at: 0 }; const followUpPersistedRows = []; function fakeFollowUpDbQuery(sql, params) { const s = String(sql); if (s.includes("INSERT INTO dashboard_assistant_messages")) { followUpPersistedRows.push({ sql: s, params }); return Promise.resolve([]); } if (s.includes("CREATE TABLE")) return Promise.resolve([]); if (s.includes("WHERE id = ? AND user_email = ?")) return Promise.resolve([FOLLOWUP_CHAT_ROW]); if (s.includes("SELECT COUNT(*)")) return Promise.resolve([{ total: 0 }]); if (s.includes("WHERE id = ? LIMIT 1")) return Promise.resolve([FOLLOWUP_CHAT_ROW]); return Promise.resolve([]); } // --------------------------------------------------------------------------- // Permissive/failing scenarios first — every one of them needs // retired === false, and the retirement flag never un-flips. // --------------------------------------------------------------------------- test("the process starts unattempted and unretired (ordering anchor)", () => { const state = getAssistantProviderSecretMigrationState(); assert.strictEqual(state.attempted, false); assert.strictEqual(state.retired, false); }); test("boot window: before the first migration attempt the guard stays permissive", async () => { await withGuardEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => { const { deps } = createGuardDeps( { DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET) }, { failWrites: 1 } ); const service = createDashboardAssistantService(deps); // The queued migration attempt fires mid-body and its failing write logs // an abort warning — capture it so nothing leaks into the runner output. await captureConsoleAsync(async () => { // Synchronous call: the body up to the guard runs before the queued // setImmediate migration attempt, i.e. in the boot window. const error = await catchRejection(service.transcribeAudio({ buffer: Buffer.alloc(0) })); assert.strictEqual(error.message, NO_AUDIO_MESSAGE, "the boot window must not fire the guard"); // The first attempt then fires and records itself — but (deliberately // failing write below) retirement stays unconfirmed for the next tests. await afterImmediate(); }); const state = getAssistantProviderSecretMigrationState(); assert.strictEqual(state.attempted, true); assert.strictEqual(state.retired, false); }); }); test("guard fires on the chat path once the migration has been attempted but not retired", async () => { await withGuardEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => { const { deps } = createGuardDeps( { DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET) }, { failWrites: 1 } ); const service = createDashboardAssistantService(deps); // Capture the failing-migration window and the guard-firing call: the // abort warning and the rate-limited "blocked request" error must not // leak into the runner output. await captureConsoleAsync(async () => { await afterImmediate(); // attempted: true, retired: false (write failed) const error = await catchRejection(service.transcribeAudio({ buffer: Buffer.alloc(0) })); assertGuardErrorMessage(error, "Groq"); }); }); }); test("rate-limited visibility: one console.error per provider per window even across repeated guard fires", async () => { await withGuardEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => { const { deps } = createGuardDeps( { DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET) }, { failWrites: 1 } ); const service = createDashboardAssistantService(deps); const { result: [, secondError], lines } = await captureConsoleAsync(async () => { await afterImmediate(); // attempted: true, retired: false const first = await catchRejection(service.transcribeAudio({ buffer: Buffer.alloc(0) })); const second = await catchRejection(service.transcribeAudio({ buffer: Buffer.alloc(0) })); return [first, second]; }); assertGuardErrorMessage(secondError, "Groq"); const blockedLines = lines.error.filter((line) => line.includes("blocked request")); assert.strictEqual(blockedLines.length, 1, "the second fire within the window must stay silent server-side"); assert.ok( blockedLines[0].includes("groq key still uses the legacy enc-v1 envelope (weak legacy chain active); awaiting migration/re-save"), "the log line must name the condition and the wait state" ); for (const line of [...lines.error, ...lines.warn, ...lines.log]) { assertNoSecrets(line); } }); }); test("an enc-v2 key never triggers the guard while an enc-v1 provider still does (per-provider scoping)", async () => { await withGuardEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => { const encV2Groq = encryptAssistantProviderToken("fresh-groq-enc-v2-key"); const { deps } = createGuardDeps( { DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: encV2Groq, DASHBOARD_ASSISTANT_GOOGLE_AI_API_KEY_ENCRYPTED: legacyEncryptV1(GOOGLE_PLAINTEXT, DEDICATED_SECRET), DASHBOARD_ASSISTANT_PROVIDER: "groq", }, { failWrites: 1 } ); const groqService = createDashboardAssistantService(deps); // Capture both failing-migration windows and the guard-firing call: the // abort warnings and the rate-limited "blocked request" error must not // leak into the runner output. await captureConsoleAsync(async () => { await afterImmediate(); // Groq wears enc-v2: the guard must not fire even though the migration // failed and retirement is unconfirmed (Google's enc-v1 keeps it there). const groqError = await catchRejection(groqService.transcribeAudio({ buffer: Buffer.alloc(0) })); assert.strictEqual(groqError.message, NO_AUDIO_MESSAGE); // Same process, same weak state, but the RESOLVED provider wears enc-v1: // the guard fires for it — scoping is per provider, exactly as stored. const { deps: googleDeps } = createGuardDeps( { DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: encV2Groq, DASHBOARD_ASSISTANT_GOOGLE_AI_API_KEY_ENCRYPTED: legacyEncryptV1(GOOGLE_PLAINTEXT, DEDICATED_SECRET), DASHBOARD_ASSISTANT_PROVIDER: "google", }, { failWrites: 1 } ); const googleService = createDashboardAssistantService(googleDeps); await afterImmediate(); const googleError = await catchRejection(googleService.transcribeAudio({ buffer: Buffer.alloc(0) })); assertGuardErrorMessage(googleError, "Google AI Studio"); }); }); }); test("the legacy plaintext fallback is not an envelope version: the guard leaves it alone", async () => { await withGuardEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => { // Groq resolves through the pre-existing PLAINTEXT env fallback (a // pre-existing at-rest hygiene issue, deliberately out of the guard's // scope); Google's decryptable enc-v1 value keeps retirement unconfirmed // so the permissive outcome below is attributable to the version rule. const { deps } = createGuardDeps( { GROQ_API_KEY: "gsk-plaintext-fallback-key-not-an-envelope", DASHBOARD_ASSISTANT_GOOGLE_AI_API_KEY_ENCRYPTED: legacyEncryptV1(GOOGLE_PLAINTEXT, DEDICATED_SECRET), }, { failWrites: 1 } ); const service = createDashboardAssistantService(deps); // Capture the failing-migration window: the abort warning must not leak // into the runner output. await captureConsoleAsync(async () => { await afterImmediate(); const error = await catchRejection(service.transcribeAudio({ buffer: Buffer.alloc(0) })); assert.strictEqual(error.message, NO_AUDIO_MESSAGE, "a plaintext-resolved key must not fire the guard"); }); }); }); test("an undecryptable enc-v1 value resolves to no key and keeps the existing not-configured behavior", async () => { await withGuardEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => { const { deps } = createGuardDeps( { DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: legacyEncryptV1(GROQ_PLAINTEXT, "lost-secret") }, { failWrites: 1 } ); const service = createDashboardAssistantService(deps); const { lines } = await captureConsoleAsync(async () => { await afterImmediate(); const error = await catchRejection(service.transcribeAudio({ buffer: Buffer.alloc(0) })); assert.strictEqual( error.message, "Groq is not configured.", "no resolvable key means the pre-existing path handles it — no double error" ); }); // The guard stayed silent while the cache load's decrypt failure was // logged as usual. assert.ok(!lines.error.some((line) => line.includes("legacy encryption envelope"))); assert.ok(lines.error.some((line) => line.includes("Failed to decrypt groq API key"))); }); }); test("re-saving the provider key (enc-v2) heals the guard condition", async () => { await withGuardEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => { // Both variants' guard fires and failing-migration windows log to the // console — capture the whole scenario so nothing leaks into the runner // output. await captureConsoleAsync(async () => { // Variant 1, realistic invalidation path: the save bumps the .env mtime, // the next ensureProviderSecretCache reloads and refreshes the version. const { env, deps, allowWrites } = createGuardDeps( { DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET) }, { failWrites: 1 } ); const service = createDashboardAssistantService(deps); await afterImmediate(); await catchRejection(service.transcribeAudio({ buffer: Buffer.alloc(0) })); // guard fires allowWrites(); const saved = await service.saveProviderToken({ provider: "groq", token: "gsk-groq-test-key-0123456789abcdef" }); assert.strictEqual(saved.configured, true); assert.strictEqual( env.DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED.split(":")[0], "enc-v2", "the re-save must store an enc-v2 envelope" ); const error = await catchRejection(service.transcribeAudio({ buffer: Buffer.alloc(0) })); assert.strictEqual(error.message, NO_AUDIO_MESSAGE, "the re-saved provider must serve chats again"); // Variant 2, cache-only path: NO mtime dep at all (mtime check disabled, // TTL far away) — the in-place cache mirror in saveProviderToken must // clear the condition immediately, without any reload. const { deps: depsNoMtime, allowWrites: allowWritesNoMtime } = createGuardDeps( { DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET) }, { failWrites: 1, withMtime: false } ); const serviceNoMtime = createDashboardAssistantService(depsNoMtime); await afterImmediate(); await catchRejection(serviceNoMtime.transcribeAudio({ buffer: Buffer.alloc(0) })); // guard fires allowWritesNoMtime(); await serviceNoMtime.saveProviderToken({ provider: "groq", token: "gsk-groq-test-key-0123456789abcdef" }); const errorNoMtime = await catchRejection(serviceNoMtime.transcribeAudio({ buffer: Buffer.alloc(0) })); assert.strictEqual(errorNoMtime.message, NO_AUDIO_MESSAGE, "the in-place envelopeVersions refresh must heal the guard"); }); }); }); test("an mtime-triggered cache reload alone heals the guard condition (cross-worker re-save without saveProviderToken)", async () => { await withGuardEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => { // A sibling pm2 worker re-saves the groq key: the shared .env's encrypted // value becomes a fresh enc-v2 envelope and its atomic rename bumps the // mtime. This process never calls saveProviderToken, so no in-place cache // mirror can hide the mechanism — only the cross-worker mtime // invalidation (ensureProviderSecretCache's reload gate) can heal the // guard here, which attributes the healing to the reload itself. const { env, deps, bumpMtime } = createGuardDeps( { DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET) }, { failWrites: 1 } ); const service = createDashboardAssistantService(deps); await captureConsoleAsync(async () => { await afterImmediate(); // attempted: true, retired: false (write failed) await catchRejection(service.transcribeAudio({ buffer: Buffer.alloc(0) })); // guard fires // The sibling's re-save lands in .env without this process's help. env.DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED = encryptAssistantProviderToken("gsk-groq-sibling-worker-key-0123456789abcdef"); bumpMtime(); // the atomic-rename mtime bump that invalidates the cache const error = await catchRejection(service.transcribeAudio({ buffer: Buffer.alloc(0) })); assert.strictEqual(error.message, NO_AUDIO_MESSAGE, "the mtime-triggered reload alone must clear the guard"); }); }); }); test("skipAi follow-ups stay guard-exempt (local persistence only) while provider-bound follow-ups fail closed", async () => { await withGuardEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => { const SUMMARY = "Browser check finished: the panel is healthy."; const { deps } = createGuardDeps( { DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET) }, { failWrites: 1 } ); deps.db = require("../tests/helpers/assistant-history-db").assistantHistoryDb(fakeFollowUpDbQuery); deps.findUserByEmail = async (email) => ({ id: 7, email, suspended: false }); followUpPersistedRows.length = 0; const service = createDashboardAssistantService(deps); const { result: [local, guardError] } = await captureConsoleAsync(async () => { await afterImmediate(); // attempted: true, retired: false (write failed) // skipAi=true: a client-verified follow-up with zero intended provider // traffic must NOT trip the fail-closed guard, even with a stored // enc-v1 key — it goes straight to the local persistence path, // restoring the pre-guard availability. const local = await service.completeClientFollowUp({ userEmail: "user@guard.local", chatId: FOLLOWUP_CHAT_ROW.id, summary: SUMMARY, skipAi: true, }); // skipAi=false: the follow-up resolves its key for a real provider // completion, so the guard fires exactly as on the chat path. const guardError = await catchRejection(service.completeClientFollowUp({ userEmail: "user@guard.local", chatId: FOLLOWUP_CHAT_ROW.id, summary: SUMMARY, skipAi: false, })); return [local, guardError]; }); // The local fallback ran and returned exactly as before the guard existed. assert.strictEqual(local.reply, SUMMARY, "the client summary is the reply (no provider output)"); assert.strictEqual(local.model, "adpanel-client-local"); assert.strictEqual(local.thinkingTimeMs, 0); assert.deepStrictEqual(local.clientActions, []); assert.strictEqual(local.chat.id, FOLLOWUP_CHAT_ROW.id); // And it persisted under the same provenance rules as always: the skipAi // call inserts its summary; the guard-blocked call inserts nothing. const inserts = followUpPersistedRows.filter((row) => row.sql.includes("INSERT INTO dashboard_assistant_messages")); assert.strictEqual(inserts.length, 1, "the skipAi call persists its summary; the guard-blocked call persists nothing"); assert.strictEqual(inserts[0].params[1], "user", "client text is persisted under the user role, never as model output"); assert.strictEqual(inserts[0].params[2], SUMMARY); assert.strictEqual(inserts[0].params[3], "adpanel-client-local"); assertGuardErrorMessage(guardError, "Groq"); }); }); // --------------------------------------------------------------------------- // LAST: the one retirement-confirming test. The flag is one-way per process, // so nothing after this point may need retired === false. // --------------------------------------------------------------------------- test("retirement confirmed: the guard never fires again, even for a hypothetical enc-v1 value", async () => { await withGuardEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => { // .env holds only enc-v2: the migration confirms retirement without a // write and the boot attempt below flips the flag. const { env, deps, bumpMtime } = createGuardDeps( { DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: encryptAssistantProviderToken("already-migrated-groq-key") } ); const service = createDashboardAssistantService(deps); await afterImmediate(); assert.strictEqual(getAssistantProviderSecretMigrationState().retired, true); const error = await catchRejection(service.transcribeAudio({ buffer: Buffer.alloc(0) })); assert.strictEqual(error.message, NO_AUDIO_MESSAGE, "a retired process must keep serving chats"); // Hypothetical regression: an enc-v1 value appears in .env anyway (e.g. // restored from a backup). The reload picks it up — decryptable key and // enc-v1 version in the cache — but retirement is one-way: no guard. env.DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED = legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET); bumpMtime(); // the reload trigger the mtime check needs const errorAfter = await catchRejection(service.transcribeAudio({ buffer: Buffer.alloc(0) })); assert.strictEqual(errorAfter.message, NO_AUDIO_MESSAGE, "retirement is one-way: the guard stays silent"); }); });