721 lines
34 KiB
JavaScript
721 lines
34 KiB
JavaScript
"use strict";
|
|
|
|
// Tests for the enc-v1 migration's QUARANTINE path: an enc-v1 value whose
|
|
// minting secret is lost can never decrypt again and would otherwise sit in
|
|
// its LIVE .env slot forever, holding SECRET_KEY in the legacy decryption
|
|
// chain and keeping the weak state (and the retry loop) alive. Once the SAME
|
|
// value's decryption failure is proven persistent — ASSISTANT_PROVIDER_SECRET
|
|
// _QUARANTINE_THRESHOLD (= 4) consecutive failing runs in one process, with
|
|
// the dedicated secret present and the recovery slot empty — the migration
|
|
// MOVES it to the provider's *_ORPHANED_V1 recovery slot in the run's single
|
|
// batch write: quarantine, never destruction (the ciphertext survives for
|
|
// manual recovery; artifacts are never overwritten; no runtime path reads
|
|
// them). The emptied live slot lets SECRET_KEY retirement confirm.
|
|
//
|
|
// This file runs in its own process and drives the EXPORTED
|
|
// migrateAssistantProviderSecretsV1ToV2 directly (never the scheduler — no
|
|
// service construction here, so no timers and no setImmediate runs). The
|
|
// module-wide retirement flag is one-way per process, so the same ordering
|
|
// discipline as the sibling test files applies: every test that must run
|
|
// while retirement is unconfirmed — and the ONE test that needs SECRET_KEY
|
|
// still inside the decryption chain — comes first, and the retirement-
|
|
// flipping scenarios follow. Streak state is module-wide too; every test
|
|
// mints fresh ciphertexts (random IV per legacyEncryptV1 call), so each
|
|
// test's first failing run starts a fresh streak via the value-change reset.
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
const crypto = require("crypto");
|
|
|
|
const {
|
|
decryptAssistantProviderToken,
|
|
migrateAssistantProviderSecretsV1ToV2,
|
|
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 PROVIDER_ORPHANED_ENV_KEYS = [
|
|
"DASHBOARD_ASSISTANT_GROQ_API_KEY_ORPHANED_V1",
|
|
"DASHBOARD_ASSISTANT_GOOGLE_AI_API_KEY_ORPHANED_V1",
|
|
];
|
|
|
|
const GROQ_LIVE_KEY = "DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED";
|
|
const GROQ_ORPHAN_KEY = "DASHBOARD_ASSISTANT_GROQ_API_KEY_ORPHANED_V1";
|
|
const GOOGLE_LIVE_KEY = "DASHBOARD_ASSISTANT_GOOGLE_AI_API_KEY_ENCRYPTED";
|
|
const GOOGLE_ORPHAN_KEY = "DASHBOARD_ASSISTANT_GOOGLE_AI_API_KEY_ORPHANED_V1";
|
|
|
|
// Mirrors ASSISTANT_PROVIDER_SECRET_QUARANTINE_THRESHOLD in the service (not
|
|
// exported — cross-checked by these tests' behavior: quarantine fires on the
|
|
// threshold-th consecutive run of the same value, never earlier).
|
|
const THRESHOLD = 4;
|
|
|
|
const CONTEXT = "adpanel:dashboard-assistant:provider-key:v1";
|
|
|
|
// Distinctive secret strings for the secret-free log assertions: if any of
|
|
// these ever leaks into a quarantine/migration log line, the tests must fail.
|
|
const DEDICATED_SECRET = "dedicated-secret-quarantine-suite-DO-NOT-LOG";
|
|
const GROQ_PLAINTEXT = "gsk-PLAINTEXT-GROQ-QUARANTINE-SUITE-DO-NOT-LOG";
|
|
const GOOGLE_PLAINTEXT = "AIza-PLAINTEXT-GOOGLE-QUARANTINE-SUITE-DO-NOT-LOG";
|
|
const SESSION_SECRET = "old-session-secret-quarantine-suite";
|
|
const TEST_SECRETS = [DEDICATED_SECRET, GROQ_PLAINTEXT, GOOGLE_PLAINTEXT, SESSION_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(":");
|
|
}
|
|
|
|
function withSecretEnv(overrides, fn) {
|
|
const saved = new Map(SECRET_ENV_KEYS.map((key) => [key, process.env[key]]));
|
|
try {
|
|
for (const key of SECRET_ENV_KEYS) delete process.env[key];
|
|
for (const [key, value] of Object.entries(overrides)) {
|
|
process.env[key] = value;
|
|
}
|
|
return fn();
|
|
} finally {
|
|
for (const key of SECRET_ENV_KEYS) {
|
|
const previous = saved.get(key);
|
|
if (previous === undefined) delete process.env[key];
|
|
else process.env[key] = previous;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Saves/restores the live *_ENCRYPTED slots AND the *_ORPHANED_V1 slots, so
|
|
// the migration's process.env mirror (live deletions, orphan writes) never
|
|
// leaks into other tests.
|
|
function withProviderEnv(overrides, fn) {
|
|
const keys = [...PROVIDER_ENCRYPTED_ENV_KEYS, ...PROVIDER_ORPHANED_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 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 migration deps, recording every batch
|
|
// write. Null updates apply the real "delete the line" semantics (the same
|
|
// contract index.js' writeEnvFileBatchUnderHeldLock implements).
|
|
function createEnvDeps(initialEnv) {
|
|
const env = { ...initialEnv };
|
|
const writes = [];
|
|
return {
|
|
env,
|
|
writes,
|
|
deps: {
|
|
readEnvFile: () => ({ ...env }),
|
|
writeEnvFileBatch: (updates) => {
|
|
writes.push(updates);
|
|
for (const [key, value] of Object.entries(updates)) {
|
|
if (value === null) delete env[key];
|
|
else env[key] = value;
|
|
}
|
|
return true;
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
// Like createEnvDeps, but the fake deps also expose writeEnvFileBatchVerified
|
|
// (the writer production wires): unless verifiedResult === false it applies
|
|
// the batch and records every call — updates PLUS the expectedOriginals it
|
|
// was handed — so tests can pin the emptiness assertion for the destination
|
|
// slot. `writes` keeps recording ONLY plain writeEnvFileBatch calls.
|
|
function createVerifiedEnvDeps(initialEnv, verifiedResult) {
|
|
const base = createEnvDeps(initialEnv);
|
|
const verifiedCalls = [];
|
|
base.verifiedCalls = verifiedCalls;
|
|
base.deps.writeEnvFileBatchVerified = (updates, expectedOriginals) => {
|
|
verifiedCalls.push({ updates, expectedOriginals });
|
|
if (verifiedResult === false) return false;
|
|
for (const [key, value] of Object.entries(updates)) {
|
|
if (value === null) delete base.env[key];
|
|
else base.env[key] = value;
|
|
}
|
|
return true;
|
|
};
|
|
return base;
|
|
}
|
|
|
|
// Captures console.warn, console.log AND console.error (the quarantine move
|
|
// logs via console.error) so tests can assert the log lines and so nothing
|
|
// leaks into the runner output.
|
|
function captureConsole(fn) {
|
|
const lines = [];
|
|
const originals = { warn: console.warn, log: console.log, error: console.error };
|
|
for (const level of Object.keys(originals)) {
|
|
console[level] = (...args) => lines.push(args.join(" "));
|
|
}
|
|
try {
|
|
return { result: fn(), lines };
|
|
} finally {
|
|
console.warn = originals.warn;
|
|
console.log = originals.log;
|
|
console.error = originals.error;
|
|
}
|
|
}
|
|
|
|
function assertNoSecrets(lines) {
|
|
for (const secret of TEST_SECRETS) {
|
|
assert.ok(
|
|
lines.every((line) => !line.includes(secret)),
|
|
`no log line may contain the test secret ${JSON.stringify(secret)}`
|
|
);
|
|
}
|
|
}
|
|
|
|
// No log line may carry key material in ANY form: not the plaintext tokens,
|
|
// not the secrets, not the stored envelopes (ciphertext is sensitive too).
|
|
function assertNoKeyMaterial(lines, envelopes = []) {
|
|
assertNoSecrets(lines);
|
|
for (const envelope of envelopes) {
|
|
assert.ok(
|
|
lines.every((line) => !line.includes(envelope)),
|
|
"no log line may contain a stored envelope string"
|
|
);
|
|
}
|
|
}
|
|
|
|
function quarantineLines(lines) {
|
|
return lines.filter((line) => line.includes("quarantined an undecryptable legacy enc-v1 key"));
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Scenarios that must run BEFORE the retirement flag flips (and before
|
|
// SECRET_KEY leaves the chain). Each run here fails at least one value, so
|
|
// none of them flips the one-way flag.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("runs 1..threshold-1 keep the undecryptable value live, slotless and unretired", () => {
|
|
withSecretEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, () =>
|
|
withProviderEnv({}, () => {
|
|
const lostValue = legacyEncryptV1(GROQ_PLAINTEXT, "lost-secret");
|
|
const { env, writes, deps } = createEnvDeps({ [GROQ_LIVE_KEY]: lostValue });
|
|
|
|
for (let run = 1; run < THRESHOLD; run += 1) {
|
|
const { result: outcome, lines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
|
|
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 }, `run ${run} must not retire or migrate`);
|
|
assert.strictEqual(env[GROQ_LIVE_KEY], lostValue, `run ${run}: the live value stays byte-identical`);
|
|
assert.strictEqual(env[GROQ_ORPHAN_KEY], undefined, `run ${run}: no recovery slot may be created yet`);
|
|
assert.strictEqual(writes.length, 0, `run ${run}: nothing to write before the threshold`);
|
|
assert.strictEqual(quarantineLines(lines).length, 0, `run ${run}: no quarantine log line yet`);
|
|
assert.strictEqual(
|
|
getAssistantProviderSecretMigrationState().lastFailureReason,
|
|
"undecryptable-value",
|
|
`run ${run}: the pre-existing failure reason is unchanged`
|
|
);
|
|
assertNoKeyMaterial(lines, [lostValue]);
|
|
}
|
|
})
|
|
);
|
|
});
|
|
|
|
test("an occupied ORPHANED_V1 slot is never overwritten and never triggers a move", () => {
|
|
withSecretEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, () =>
|
|
withProviderEnv({}, () => {
|
|
const liveValue = legacyEncryptV1(GROQ_PLAINTEXT, "lost-secret-newer");
|
|
const existingArtifact = legacyEncryptV1("artifact-from-an-earlier-boot", "lost-secret-older");
|
|
const { env, writes, deps } = createEnvDeps({
|
|
[GROQ_LIVE_KEY]: liveValue,
|
|
[GROQ_ORPHAN_KEY]: existingArtifact,
|
|
});
|
|
|
|
// Well past the threshold: the occupied slot is an ABSOLUTE invariant —
|
|
// quarantine never fires, the live value stays (counted as failed, so
|
|
// retirement stays blocked), and the existing artifact is untouched.
|
|
for (let run = 0; run < THRESHOLD + 2; run += 1) {
|
|
const { result: outcome, lines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
|
|
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 }, `run ${run} stays unretired`);
|
|
assert.strictEqual(env[GROQ_LIVE_KEY], liveValue, `run ${run}: the live value stays untouched`);
|
|
assert.strictEqual(
|
|
env[GROQ_ORPHAN_KEY],
|
|
existingArtifact,
|
|
`run ${run}: the existing recovery artifact is never overwritten`
|
|
);
|
|
assert.strictEqual(writes.length, 0, `run ${run}: an occupied slot means no batch write at all`);
|
|
assert.strictEqual(quarantineLines(lines).length, 0, `run ${run}: no quarantine log line`);
|
|
assertNoKeyMaterial(lines, [liveValue, existingArtifact]);
|
|
}
|
|
})
|
|
);
|
|
});
|
|
|
|
test("a missing dedicated secret never quarantines regardless of streak", () => {
|
|
// Only SESSION_SECRET is set: the value below decrypts fine via the legacy
|
|
// chain, but nothing can be minted without the dedicated secret — the
|
|
// anti-mis-quarantine invariant says a broken-provisioning environment must
|
|
// NEVER move a live value (it might decrypt once the secret lands), no
|
|
// matter how many runs have failed.
|
|
withSecretEnv({ SESSION_SECRET }, () =>
|
|
withProviderEnv({}, () => {
|
|
const stored = legacyEncryptV1(GROQ_PLAINTEXT, SESSION_SECRET);
|
|
const { env, writes, deps } = createEnvDeps({ [GROQ_LIVE_KEY]: stored });
|
|
|
|
for (let run = 0; run < THRESHOLD + 1; run += 1) {
|
|
const { result: outcome, lines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
|
|
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 }, `run ${run} stays unretired`);
|
|
assert.strictEqual(env[GROQ_LIVE_KEY], stored, `run ${run}: the value stays untouched`);
|
|
assert.strictEqual(env[GROQ_ORPHAN_KEY], undefined, `run ${run}: no recovery slot may be created`);
|
|
assert.strictEqual(writes.length, 0, `run ${run}: no batch write without a dedicated secret`);
|
|
assert.strictEqual(quarantineLines(lines).length, 0, `run ${run}: no quarantine log line`);
|
|
assert.strictEqual(
|
|
getAssistantProviderSecretMigrationState().lastFailureReason,
|
|
"missing-dedicated-secret",
|
|
`run ${run}: the actionable diagnosis is unchanged`
|
|
);
|
|
assertNoKeyMaterial(lines, [stored]);
|
|
}
|
|
})
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// First retirement flip of the process: a value decryptable under SECRET_KEY
|
|
// (the chain candidate this test needs) re-wraps on attempt 1 — pinning that
|
|
// quarantine only ever touches UNDECRYPTABLE values. Nothing after this test
|
|
// may rely on SECRET_KEY being a decryption candidate.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("a value decryptable under SECRET_KEY re-wraps on attempt 1 and is never quarantined", () => {
|
|
withSecretEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET, SECRET_KEY: "recaptcha-site-secret" }, () =>
|
|
withProviderEnv({}, () => {
|
|
const secretKeyValue = legacyEncryptV1(GROQ_PLAINTEXT, "recaptcha-site-secret");
|
|
const { env, writes, deps } = createEnvDeps({ [GROQ_LIVE_KEY]: secretKeyValue });
|
|
|
|
const { result: outcome, lines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
|
|
// The value re-wrapped normally: a decryptable value is never a
|
|
// quarantine candidate, no recovery slot exists, and the full success
|
|
// (first flip of the one-way flag) retires SECRET_KEY out of the chain.
|
|
assert.deepStrictEqual(outcome, { retired: true, migrated: 1 });
|
|
assert.strictEqual(env[GROQ_ORPHAN_KEY], undefined, "a decryptable value must never create a recovery slot");
|
|
assert.strictEqual(env[GROQ_LIVE_KEY].split(":")[0], "enc-v2");
|
|
assert.strictEqual(decryptAssistantProviderToken(env[GROQ_LIVE_KEY]), GROQ_PLAINTEXT);
|
|
assert.strictEqual(writes.length, 1);
|
|
assert.strictEqual(quarantineLines(lines).length, 0);
|
|
assertNoKeyMaterial(lines, [secretKeyValue]);
|
|
})
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Retirement-flipping scenarios. The flag is already true here; every
|
|
// retired/unretired assertion below reads the run's OUTCOME (driven by
|
|
// failed === 0), which is independent of the prior flag state.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("a changed value resets its failure streak and needs threshold fresh runs", () => {
|
|
withSecretEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, () =>
|
|
withProviderEnv({}, () => {
|
|
const valueA = legacyEncryptV1(GROQ_PLAINTEXT, "lost-secret-A");
|
|
const { env, writes, deps } = createEnvDeps({ [GROQ_LIVE_KEY]: valueA });
|
|
|
|
// Three failing runs of valueA: streak 3 — one short of quarantine.
|
|
for (let run = 0; run < THRESHOLD - 1; run += 1) {
|
|
const { result: outcome, lines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 });
|
|
assert.strictEqual(env[GROQ_LIVE_KEY], valueA);
|
|
assert.strictEqual(writes.length, 0);
|
|
assertNoKeyMaterial(lines, [valueA]);
|
|
}
|
|
|
|
// Re-mint a DIFFERENT undecryptable envelope (e.g. the value was
|
|
// re-saved under another now-lost secret): the fresh ciphertext gets
|
|
// the full benefit of the doubt — the 4th run overall must NOT
|
|
// quarantine, because it is only the 1st failure of valueB.
|
|
const valueB = legacyEncryptV1(GROQ_PLAINTEXT, "lost-secret-B");
|
|
env[GROQ_LIVE_KEY] = valueB;
|
|
|
|
for (let run = 0; run < THRESHOLD - 1; run += 1) {
|
|
const { result: outcome, lines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 }, `valueB run ${run + 1} must not quarantine yet`);
|
|
assert.strictEqual(env[GROQ_LIVE_KEY], valueB, "valueB stays live");
|
|
assert.strictEqual(env[GROQ_ORPHAN_KEY], undefined, "no recovery slot before valueB's own threshold");
|
|
assert.strictEqual(writes.length, 0);
|
|
assertNoKeyMaterial(lines, [valueA, valueB]);
|
|
}
|
|
|
|
// valueB's 4th consecutive failure: NOW the move fires, carrying
|
|
// exactly valueB (never any residue of valueA).
|
|
const { result: outcome, lines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
assert.deepStrictEqual(outcome, { retired: true, migrated: 0 });
|
|
assert.strictEqual(env[GROQ_LIVE_KEY], undefined);
|
|
assert.strictEqual(env[GROQ_ORPHAN_KEY], valueB, "the moved value is exactly the current ciphertext");
|
|
assert.strictEqual(quarantineLines(lines).length, 1);
|
|
assertNoKeyMaterial(lines, [valueA, valueB]);
|
|
})
|
|
);
|
|
});
|
|
|
|
test("run #threshold quarantines: exact move, process.env mirror, one loud log, streak cleared", () => {
|
|
withSecretEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, () =>
|
|
withProviderEnv({}, () => {
|
|
const lostValue = legacyEncryptV1(GROQ_PLAINTEXT, "lost-secret");
|
|
const { env, writes, deps } = createEnvDeps({ [GROQ_LIVE_KEY]: lostValue });
|
|
|
|
// Runs 1-3: quiet, unretired (covered in detail by the first test).
|
|
for (let run = 1; run < THRESHOLD; run += 1) {
|
|
captureConsole(() => migrateAssistantProviderSecretsV1ToV2(deps));
|
|
}
|
|
|
|
// Run 4 — the threshold run: the move fires.
|
|
const { result: outcome, lines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
|
|
assert.deepStrictEqual(outcome, { retired: true, migrated: 0 }, "quarantine handles the value: nothing blocks retirement");
|
|
assert.strictEqual(writes.length, 1, "exactly one batch write");
|
|
assert.deepStrictEqual(
|
|
writes[0],
|
|
{ [GROQ_LIVE_KEY]: null, [GROQ_ORPHAN_KEY]: lostValue },
|
|
"the batch deletes the live line and stores the EXACT original envelope in the recovery slot"
|
|
);
|
|
assert.strictEqual(env[GROQ_LIVE_KEY], undefined, "the live slot is gone from .env");
|
|
assert.strictEqual(env[GROQ_ORPHAN_KEY], lostValue, "the recovery slot holds the exact original envelope");
|
|
assert.strictEqual(process.env[GROQ_LIVE_KEY], undefined, "the live key is mirrored out of process.env");
|
|
assert.strictEqual(process.env[GROQ_ORPHAN_KEY], lostValue, "the recovery slot is mirrored into process.env");
|
|
|
|
// Exactly ONE loud, secret-free console.error naming both keys and the
|
|
// attempt count, with both remediations.
|
|
const moves = quarantineLines(lines);
|
|
assert.strictEqual(moves.length, 1, "one quarantine log line per quarantined provider");
|
|
assert.ok(moves[0].includes("for Groq:"), "the line names the provider label");
|
|
assert.ok(moves[0].includes(GROQ_LIVE_KEY) && moves[0].includes(GROQ_ORPHAN_KEY), "the line names both env keys");
|
|
assert.ok(moves[0].includes(`after ${THRESHOLD} undecryptable attempt(s)`), "the line names the attempt count");
|
|
assert.ok(moves[0].includes("Recover:") && moves[0].includes("Discard:"), "the line carries both remediations");
|
|
assertNoKeyMaterial(lines, [lostValue]);
|
|
|
|
// Streak cleared: simulate the operator discarding the artifact and a
|
|
// backup restore putting the same value back into the live slot. If
|
|
// the streak had survived, the very first run would re-quarantine;
|
|
// cleared, it takes threshold fresh runs again.
|
|
delete env[GROQ_ORPHAN_KEY];
|
|
env[GROQ_LIVE_KEY] = lostValue;
|
|
for (let run = 1; run < THRESHOLD; run += 1) {
|
|
const { result: reoutcome, lines: relines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
assert.deepStrictEqual(reoutcome, { retired: false, migrated: 0 }, `post-cleanup run ${run} must not re-quarantine`);
|
|
assert.strictEqual(env[GROQ_LIVE_KEY], lostValue, `post-cleanup run ${run}: the restored value stays live`);
|
|
assert.strictEqual(quarantineLines(relines).length, 0);
|
|
assertNoKeyMaterial(relines, [lostValue]);
|
|
}
|
|
})
|
|
);
|
|
});
|
|
|
|
test("a refused quarantine write keeps the live value, persists the streak, and the next successful run moves it", () => {
|
|
withSecretEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, () =>
|
|
withProviderEnv({}, () => {
|
|
const lostValue = legacyEncryptV1(GROQ_PLAINTEXT, "lost-secret");
|
|
const { env, writes, deps } = createEnvDeps({ [GROQ_LIVE_KEY]: lostValue });
|
|
deps.writeEnvFileBatch = () => false; // simulated read-only .env
|
|
|
|
// Runs 1-3 fail quietly; run 4 reaches the threshold and attempts the
|
|
// move — but the write fails, so the abort path covers it: live value
|
|
// intact, no orphan, no quarantine log, retirement blocked.
|
|
for (let run = 1; run < THRESHOLD; run += 1) {
|
|
const { result: outcome, lines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 });
|
|
assert.strictEqual(quarantineLines(lines).length, 0);
|
|
assertNoKeyMaterial(lines, [lostValue]);
|
|
}
|
|
const { result: thresholdOutcome, lines: thresholdLines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
assert.deepStrictEqual(thresholdOutcome, { retired: false, migrated: 0 }, "a failed quarantine write blocks retirement");
|
|
assert.strictEqual(env[GROQ_LIVE_KEY], lostValue, "the live value stays byte-identical");
|
|
assert.strictEqual(env[GROQ_ORPHAN_KEY], undefined, "no orphan slot may appear from a failed write");
|
|
assert.ok(
|
|
thresholdLines.some((line) => line.includes("enc-v1 migration aborted: .env update failed")),
|
|
"the existing abort warning covers the failed move — no new log line"
|
|
);
|
|
assert.strictEqual(quarantineLines(thresholdLines).length, 0, "no quarantine log line when the write failed");
|
|
assertNoKeyMaterial(thresholdLines, [lostValue]);
|
|
|
|
// The streak persisted across the failed write: the next run against a
|
|
// healable .env quarantines immediately (no fresh threshold needed).
|
|
deps.writeEnvFileBatch = (updates) => {
|
|
writes.push(updates);
|
|
for (const [key, value] of Object.entries(updates)) {
|
|
if (value === null) delete env[key];
|
|
else env[key] = value;
|
|
}
|
|
return true;
|
|
};
|
|
const { result: healedOutcome, lines: healedLines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
assert.deepStrictEqual(healedOutcome, { retired: true, migrated: 0 }, "the retry heals the move");
|
|
assert.strictEqual(env[GROQ_LIVE_KEY], undefined);
|
|
assert.strictEqual(env[GROQ_ORPHAN_KEY], lostValue);
|
|
assert.strictEqual(quarantineLines(healedLines).length, 1);
|
|
assertNoKeyMaterial(healedLines, [lostValue]);
|
|
})
|
|
);
|
|
});
|
|
|
|
test("the verified writer receives the emptiness assertion for the destination slot", () => {
|
|
withSecretEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, () =>
|
|
withProviderEnv({}, () => {
|
|
const lostValue = legacyEncryptV1(GROQ_PLAINTEXT, "lost-secret");
|
|
const { env, writes, verifiedCalls, deps } = createVerifiedEnvDeps({ [GROQ_LIVE_KEY]: lostValue });
|
|
|
|
for (let run = 1; run < THRESHOLD; run += 1) {
|
|
captureConsole(() => migrateAssistantProviderSecretsV1ToV2(deps));
|
|
}
|
|
const { result: outcome, lines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
|
|
assert.deepStrictEqual(outcome, { retired: true, migrated: 0 });
|
|
assert.strictEqual(verifiedCalls.length, 1, "the threshold run writes through the verified writer");
|
|
// The race-closing contract: expectedOriginals pins the live value AND
|
|
// asserts the destination slot is still EMPTY under the .env lock — two
|
|
// workers quarantining different values cannot both win, the loser's
|
|
// whole batch is refused.
|
|
assert.deepStrictEqual(verifiedCalls[0].expectedOriginals, {
|
|
[GROQ_LIVE_KEY]: lostValue,
|
|
[GROQ_ORPHAN_KEY]: "",
|
|
});
|
|
assert.deepStrictEqual(verifiedCalls[0].updates, {
|
|
[GROQ_LIVE_KEY]: null,
|
|
[GROQ_ORPHAN_KEY]: lostValue,
|
|
});
|
|
assert.strictEqual(writes.length, 0, "the plain writer must not be called when the verified writer exists");
|
|
assert.strictEqual(env[GROQ_ORPHAN_KEY], lostValue);
|
|
assertNoKeyMaterial(lines, [lostValue]);
|
|
})
|
|
);
|
|
});
|
|
|
|
test("two undecryptable providers quarantine in ONE batch write", () => {
|
|
withSecretEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, () =>
|
|
withProviderEnv({}, () => {
|
|
const groqValue = legacyEncryptV1(GROQ_PLAINTEXT, "lost-secret-groq");
|
|
const googleValue = legacyEncryptV1(GOOGLE_PLAINTEXT, "lost-secret-google");
|
|
const { env, writes, deps } = createEnvDeps({
|
|
[GROQ_LIVE_KEY]: groqValue,
|
|
[GOOGLE_LIVE_KEY]: googleValue,
|
|
});
|
|
|
|
for (let run = 1; run < THRESHOLD; run += 1) {
|
|
captureConsole(() => migrateAssistantProviderSecretsV1ToV2(deps));
|
|
}
|
|
const { result: outcome, lines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
|
|
assert.deepStrictEqual(outcome, { retired: true, migrated: 0 });
|
|
assert.strictEqual(writes.length, 1, "both providers must move in a single batch write");
|
|
assert.deepStrictEqual(writes[0], {
|
|
[GROQ_LIVE_KEY]: null,
|
|
[GROQ_ORPHAN_KEY]: groqValue,
|
|
[GOOGLE_LIVE_KEY]: null,
|
|
[GOOGLE_ORPHAN_KEY]: googleValue,
|
|
});
|
|
assert.strictEqual(env[GROQ_LIVE_KEY], undefined);
|
|
assert.strictEqual(env[GROQ_ORPHAN_KEY], groqValue);
|
|
assert.strictEqual(env[GOOGLE_LIVE_KEY], undefined);
|
|
assert.strictEqual(env[GOOGLE_ORPHAN_KEY], googleValue);
|
|
// One loud line per provider, each naming its own keys.
|
|
const moves = quarantineLines(lines);
|
|
assert.strictEqual(moves.length, 2, "one quarantine log line per quarantined provider");
|
|
assert.ok(moves.some((line) => line.includes("for Groq:") && line.includes(GROQ_ORPHAN_KEY)));
|
|
assert.ok(moves.some((line) => line.includes("for Google AI Studio:") && line.includes(GOOGLE_ORPHAN_KEY)));
|
|
assertNoKeyMaterial(lines, [groqValue, googleValue]);
|
|
})
|
|
);
|
|
});
|
|
|
|
test("a mixed run re-wraps one provider and quarantines the other in the same batch", () => {
|
|
withSecretEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, () =>
|
|
withProviderEnv({}, () => {
|
|
const groqValue = legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET); // decryptable
|
|
const googleValue = legacyEncryptV1(GOOGLE_PLAINTEXT, "lost-secret-google");
|
|
const { env, writes, deps } = createEnvDeps({
|
|
[GROQ_LIVE_KEY]: groqValue,
|
|
[GOOGLE_LIVE_KEY]: googleValue,
|
|
});
|
|
// Hold writes back until the google streak reaches the threshold: the
|
|
// groq re-wrap then retries on every run (its live slot stays enc-v1),
|
|
// so run #threshold carries the re-wrap AND the quarantine move in one
|
|
// batch — the exact mixed-write shape production can produce.
|
|
deps.writeEnvFileBatch = () => false;
|
|
|
|
for (let run = 1; run < THRESHOLD; run += 1) {
|
|
const { result: outcome } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 }, `held run ${run} aborts as today`);
|
|
assert.strictEqual(env[GROQ_LIVE_KEY], groqValue, `held run ${run}: groq stays enc-v1`);
|
|
assert.strictEqual(env[GOOGLE_LIVE_KEY], googleValue, `held run ${run}: google stays untouched`);
|
|
}
|
|
|
|
deps.writeEnvFileBatch = (updates) => {
|
|
writes.push(updates);
|
|
for (const [key, value] of Object.entries(updates)) {
|
|
if (value === null) delete env[key];
|
|
else env[key] = value;
|
|
}
|
|
return true;
|
|
};
|
|
const { result: outcome, lines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
|
|
assert.deepStrictEqual(outcome, { retired: true, migrated: 1 }, "the re-wrap counts as migrated; the move handles google");
|
|
assert.strictEqual(writes.length, 1, "re-wrap and move ride ONE batch");
|
|
assert.strictEqual(Object.keys(writes[0]).length, 3, "the batch carries exactly the three changed entries");
|
|
assert.strictEqual(writes[0][GOOGLE_LIVE_KEY], null);
|
|
assert.strictEqual(writes[0][GOOGLE_ORPHAN_KEY], googleValue);
|
|
assert.strictEqual(writes[0][GROQ_LIVE_KEY].split(":")[0], "enc-v2", "groq re-wraps in the same batch");
|
|
assert.strictEqual(decryptAssistantProviderToken(writes[0][GROQ_LIVE_KEY]), GROQ_PLAINTEXT);
|
|
assert.strictEqual(env[GROQ_ORPHAN_KEY], undefined, "the decryptable provider never gets a recovery slot");
|
|
assert.strictEqual(env[GOOGLE_LIVE_KEY], undefined);
|
|
assert.strictEqual(env[GOOGLE_ORPHAN_KEY], googleValue);
|
|
assert.ok(
|
|
lines.some((line) => line.includes("re-encrypted 1 provider API key(s) as enc-v2 under DASHBOARD_ASSISTANT_ENCRYPTION_SECRET")),
|
|
"the re-wrap outcome is logged as usual"
|
|
);
|
|
const moves = quarantineLines(lines);
|
|
assert.strictEqual(moves.length, 1, "one quarantine log line, for google only");
|
|
assert.ok(moves[0].includes("for Google AI Studio:"));
|
|
assertNoKeyMaterial(lines, [groqValue, googleValue]);
|
|
})
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// The decryptedOk gate: a value whose plaintext WAS recovered (decryption
|
|
// succeeded) but whose re-encryption keeps failing is provably NOT an orphan
|
|
// — it must never accrue streak credit and never be quarantined, no matter
|
|
// how many runs fail. It stays live and loud (failed += 1 blocks retirement)
|
|
// until the crypto layer works again. Placed with the other end-of-file
|
|
// scenarios: its final run (cipher restored) re-wraps and flips retirement.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("a decryptable value whose re-encryption fails persistently is never quarantined", () => {
|
|
withSecretEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, () =>
|
|
withProviderEnv({}, () => {
|
|
// Minted under the dedicated secret, so the legacy-chain decryption
|
|
// succeeds on every run — only the mint side will fail.
|
|
const groqValue = legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET);
|
|
const { env, writes, deps } = createEnvDeps({
|
|
[GROQ_LIVE_KEY]: groqValue,
|
|
});
|
|
|
|
const realCreateCipheriv = crypto.createCipheriv;
|
|
try {
|
|
crypto.createCipheriv = () => {
|
|
throw new Error("simulated cipher failure");
|
|
};
|
|
for (let run = 1; run <= THRESHOLD + 1; run += 1) {
|
|
const { result: outcome, lines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 }, `mint-failing run ${run} must not retire`);
|
|
assert.strictEqual(env[GROQ_LIVE_KEY], groqValue, `mint-failing run ${run}: the value we can decrypt stays live`);
|
|
assert.strictEqual(env[GROQ_ORPHAN_KEY], undefined, `mint-failing run ${run}: no recovery slot may ever be created`);
|
|
assert.strictEqual(writes.length, 0, `mint-failing run ${run}: nothing to write`);
|
|
assert.strictEqual(quarantineLines(lines).length, 0, `mint-failing run ${run}: no quarantine log`);
|
|
}
|
|
} finally {
|
|
crypto.createCipheriv = realCreateCipheriv;
|
|
}
|
|
|
|
// With the cipher working again, the same value re-wraps immediately
|
|
// (no streak credit was ever accrued) and retirement confirms — with
|
|
// no orphan slot at any point.
|
|
const { result: outcome, lines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
assert.deepStrictEqual(outcome, { retired: true, migrated: 1 }, "the value re-wraps once the mint works");
|
|
assert.strictEqual(env[GROQ_ORPHAN_KEY], undefined, "still no recovery slot");
|
|
assert.strictEqual(quarantineLines(lines).length, 0);
|
|
assertNoKeyMaterial(lines, [groqValue, GROQ_PLAINTEXT]);
|
|
})
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// LAST: the nothing-to-do retire path. The flag is one-way, so this final
|
|
// test documents its shape (same process, flag/streak state warm): an .env
|
|
// that already holds a recovery artifact and no live enc-v1 retires
|
|
// immediately and writes nothing.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("nothing-to-do retire: an occupied orphan slot plus no live enc-v1 retires without touching .env", () => {
|
|
withSecretEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, () =>
|
|
withProviderEnv({}, () => {
|
|
const artifact = legacyEncryptV1(GROQ_PLAINTEXT, "lost-secret");
|
|
const { env, writes, deps } = createEnvDeps({
|
|
[GROQ_ORPHAN_KEY]: artifact,
|
|
// The live config is enc-v1-free; google stores nothing.
|
|
[GOOGLE_LIVE_KEY]: "enc-v2:AAAA:BBBB:CCCC:DDDD",
|
|
});
|
|
|
|
const { result: outcome, lines } = captureConsole(() =>
|
|
migrateAssistantProviderSecretsV1ToV2(deps)
|
|
);
|
|
|
|
assert.deepStrictEqual(outcome, { retired: true, migrated: 0 }, "the first run retires immediately");
|
|
assert.strictEqual(writes.length, 0, "re-confirmation must not touch .env (mtime is the cache signal)");
|
|
assert.strictEqual(env[GROQ_ORPHAN_KEY], artifact, "the recovery artifact survives byte-identical");
|
|
assert.strictEqual(env[GOOGLE_LIVE_KEY], "enc-v2:AAAA:BBBB:CCCC:DDDD", "enc-v2 values stay untouched");
|
|
assert.strictEqual(quarantineLines(lines).length, 0);
|
|
assertNoKeyMaterial(lines, [artifact]);
|
|
})
|
|
);
|
|
});
|