Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,717 @@
|
||||
"use strict";
|
||||
|
||||
// Tests for the enc-v1 provider-key migration's in-process self-healing: the
|
||||
// module-level migration state (getAssistantProviderSecretMigrationState) and
|
||||
// the retry scheduler wired into createDashboardAssistantService (backoff,
|
||||
// singleton unref'd timer, secret-free per-retry error line).
|
||||
//
|
||||
// This file runs in its own process, so the module-wide retirement flag starts
|
||||
// false and the tests below control it end-to-end: every failing scenario runs
|
||||
// first, exactly ONE test performs the healing retirement (the flag is one-way
|
||||
// per process), and the post-retirement tests come last.
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert");
|
||||
const crypto = require("crypto");
|
||||
|
||||
const {
|
||||
decryptAssistantProviderToken,
|
||||
migrateAssistantProviderSecretsV1ToV2,
|
||||
getAssistantProviderSecretMigrationState,
|
||||
createDashboardAssistantService,
|
||||
} = 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 CONTEXT = "adpanel:dashboard-assistant:provider-key:v1";
|
||||
|
||||
// Distinctive secret strings for the secret-free log assertions: if any of
|
||||
// these ever leaks into a migration/scheduler log line, the tests must fail.
|
||||
const DEDICATED_SECRET = "dedicated-secret-retry-suite-DO-NOT-LOG";
|
||||
const GROQ_PLAINTEXT = "gsk-PLAINTEXT-GROQ-RETRY-SUITE-DO-NOT-LOG";
|
||||
const GOOGLE_PLAINTEXT = "AIza-PLAINTEXT-GOOGLE-RETRY-SUITE-DO-NOT-LOG";
|
||||
const SESSION_SECRET = "old-session-secret-retry-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(":");
|
||||
}
|
||||
|
||||
// Async-aware env guard: the scheduled migration runs fire from setImmediate
|
||||
// while the test body awaits, so the overrides must hold until fn settles.
|
||||
async function withMigrationEnv(overrides, fn) {
|
||||
const keys = [...SECRET_ENV_KEYS, ...PROVIDER_ENCRYPTED_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 readEnvFile/writeEnvFileBatch deps.
|
||||
function createEnvDeps(initialEnv) {
|
||||
const env = { ...initialEnv };
|
||||
const writes = [];
|
||||
return {
|
||||
env,
|
||||
writes,
|
||||
deps: {
|
||||
readEnvFile: () => ({ ...env }),
|
||||
writeEnvFileBatch: (updates) => {
|
||||
writes.push(updates);
|
||||
Object.assign(env, updates);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Deps whose reads FAIL until the test heals them — the shape the retry
|
||||
// scheduler is meant to recover from: the first run(s) fail, a later run
|
||||
// (fired by the backoff timer) succeeds once the condition is gone.
|
||||
function createMutableEnvDeps() {
|
||||
const state = { env: {}, failReads: true, writes: [] };
|
||||
const deps = {
|
||||
readEnvFile: () => {
|
||||
if (state.failReads) throw new Error("simulated .env read failure");
|
||||
return { ...state.env };
|
||||
},
|
||||
writeEnvFileBatch: (updates) => {
|
||||
state.writes.push(updates);
|
||||
Object.assign(state.env, updates);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
return { state, deps };
|
||||
}
|
||||
|
||||
// Sync variant for the direct migrate() calls (like the encryption test's
|
||||
// captureConsole, but error-aware too).
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// Async variant for the scheduler tests: awaits the body so every line it
|
||||
// produces (including tick-fired retries) is captured before assertions run.
|
||||
async function captureConsoleAsync(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: await fn(), lines };
|
||||
} finally {
|
||||
console.warn = originals.warn;
|
||||
console.log = originals.log;
|
||||
console.error = originals.error;
|
||||
}
|
||||
}
|
||||
|
||||
// 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));
|
||||
}
|
||||
|
||||
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)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Module migration state: direct migrate() runs (no scheduler involved).
|
||||
// These MUST come first — the very first test locks attempts:1 for the
|
||||
// process's first migration run.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("the state getter exposes the exact cross-agent contract shape", () => {
|
||||
const state = getAssistantProviderSecretMigrationState();
|
||||
assert.deepStrictEqual(
|
||||
Object.keys(state).sort(),
|
||||
["attempted", "attempts", "lastAttemptAtMs", "lastFailureReason", "nextRetryAtMs", "retired"],
|
||||
"the getter's property names are a cross-agent contract"
|
||||
);
|
||||
assert.strictEqual(state.attempted, false);
|
||||
assert.strictEqual(state.retired, false);
|
||||
assert.strictEqual(state.attempts, 0);
|
||||
assert.strictEqual(state.lastAttemptAtMs, 0);
|
||||
assert.strictEqual(state.nextRetryAtMs, 0);
|
||||
assert.strictEqual(state.lastFailureReason, "");
|
||||
});
|
||||
|
||||
test("a failed first migration run records curated, secret-free state", () => {
|
||||
const outcome = migrateAssistantProviderSecretsV1ToV2(undefined);
|
||||
|
||||
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 });
|
||||
const state = getAssistantProviderSecretMigrationState();
|
||||
assert.strictEqual(state.attempted, true);
|
||||
assert.strictEqual(state.attempts, 1, "the first migrate run of the process");
|
||||
assert.strictEqual(state.retired, false);
|
||||
assert.strictEqual(state.lastFailureReason, "deps-unavailable");
|
||||
assert.strictEqual(state.nextRetryAtMs, 0, "a direct run never schedules a retry itself");
|
||||
assert.ok(state.lastAttemptAtMs > 0);
|
||||
|
||||
// The getter returns a fresh plain object: mutating it must not touch the
|
||||
// module state other agents read.
|
||||
state.lastFailureReason = "tampered";
|
||||
state.attempts = 999;
|
||||
assert.strictEqual(getAssistantProviderSecretMigrationState().lastFailureReason, "deps-unavailable");
|
||||
assert.strictEqual(getAssistantProviderSecretMigrationState().attempts, 1);
|
||||
});
|
||||
|
||||
test("an .env read failure records env-read-failed and keeps the existing warning", async () => {
|
||||
const attemptsBefore = getAssistantProviderSecretMigrationState().attempts;
|
||||
let outcome;
|
||||
const { lines } = captureConsole(() => {
|
||||
outcome = migrateAssistantProviderSecretsV1ToV2({
|
||||
readEnvFile: () => {
|
||||
throw new Error("simulated .env read failure");
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 });
|
||||
const state = getAssistantProviderSecretMigrationState();
|
||||
assert.strictEqual(state.attempts, attemptsBefore + 1);
|
||||
assert.strictEqual(state.retired, false);
|
||||
assert.strictEqual(state.lastFailureReason, "env-read-failed");
|
||||
assert.ok(
|
||||
lines.some((line) => line.includes("enc-v1 migration skipped: .env could not be read")),
|
||||
"the existing skip warning text must stay verbatim"
|
||||
);
|
||||
assertNoSecrets(lines);
|
||||
});
|
||||
|
||||
test("an empty-looking .env stays unconfirmed: env-read-failed, but quiet", async () => {
|
||||
await withMigrationEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => {
|
||||
const attemptsBefore = getAssistantProviderSecretMigrationState().attempts;
|
||||
let outcome;
|
||||
const { lines } = captureConsole(() => {
|
||||
outcome = migrateAssistantProviderSecretsV1ToV2({ readEnvFile: () => ({}) });
|
||||
});
|
||||
|
||||
// readEnvFile returning {} is what the real dependency does on a swallowed
|
||||
// read error, so this is an UNCONFIRMED state, not a success — but it is
|
||||
// the documented conservative choice and must not add log noise.
|
||||
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 });
|
||||
const state = getAssistantProviderSecretMigrationState();
|
||||
assert.strictEqual(state.attempts, attemptsBefore + 1);
|
||||
assert.strictEqual(state.lastFailureReason, "env-read-failed");
|
||||
assert.strictEqual(lines.length, 0, "the ambiguous empty read must stay quiet");
|
||||
});
|
||||
});
|
||||
|
||||
test("an undecryptable enc-v1 value records undecryptable-value", async () => {
|
||||
await withMigrationEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => {
|
||||
const lostValue = legacyEncryptV1(GROQ_PLAINTEXT, "lost-secret");
|
||||
const { env, deps } = createEnvDeps({
|
||||
DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: lostValue,
|
||||
});
|
||||
let outcome;
|
||||
const { lines } = captureConsole(() => {
|
||||
outcome = migrateAssistantProviderSecretsV1ToV2(deps);
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 });
|
||||
assert.strictEqual(env.DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED, lostValue, "the undecryptable value stays untouched");
|
||||
assert.strictEqual(getAssistantProviderSecretMigrationState().lastFailureReason, "undecryptable-value");
|
||||
assertNoSecrets(lines);
|
||||
});
|
||||
});
|
||||
|
||||
test("an enc-v1 value with no dedicated secret records missing-dedicated-secret", async () => {
|
||||
await withMigrationEnv({ SESSION_SECRET }, async () => {
|
||||
const stored = legacyEncryptV1(GROQ_PLAINTEXT, SESSION_SECRET);
|
||||
const { env, deps } = createEnvDeps({
|
||||
DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: stored,
|
||||
});
|
||||
let outcome;
|
||||
const { lines } = captureConsole(() => {
|
||||
outcome = migrateAssistantProviderSecretsV1ToV2(deps);
|
||||
});
|
||||
|
||||
// The value itself decrypts fine via the legacy chain — the run fails at
|
||||
// the encrypt step, so the actionable diagnosis is the missing secret.
|
||||
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 });
|
||||
assert.strictEqual(env.DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED, stored);
|
||||
assert.strictEqual(getAssistantProviderSecretMigrationState().lastFailureReason, "missing-dedicated-secret");
|
||||
assertNoSecrets(lines);
|
||||
});
|
||||
});
|
||||
|
||||
test("a missing writer records env-write-failed and keeps the existing warning", async () => {
|
||||
await withMigrationEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => {
|
||||
const stored = legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET);
|
||||
const { deps } = createEnvDeps({
|
||||
DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: stored,
|
||||
});
|
||||
delete deps.writeEnvFileBatch; // migrated > 0, but nowhere to write
|
||||
let outcome;
|
||||
const { lines } = captureConsole(() => {
|
||||
outcome = migrateAssistantProviderSecretsV1ToV2(deps);
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 });
|
||||
assert.strictEqual(getAssistantProviderSecretMigrationState().lastFailureReason, "env-write-failed");
|
||||
assert.ok(
|
||||
lines.some((line) =>
|
||||
line.includes("enc-v1 migration skipped: writeEnvFileBatch dependency is unavailable")
|
||||
),
|
||||
"the existing writer-missing warning text must stay verbatim"
|
||||
);
|
||||
assertNoSecrets(lines);
|
||||
});
|
||||
});
|
||||
|
||||
test("deps lacking readEnvFile record deps-unavailable and keep the existing warning", async () => {
|
||||
await withMigrationEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => {
|
||||
const attemptsBefore = getAssistantProviderSecretMigrationState().attempts;
|
||||
let outcome;
|
||||
const { lines } = captureConsole(() => {
|
||||
outcome = migrateAssistantProviderSecretsV1ToV2({ writeEnvFileBatch: () => true });
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 });
|
||||
const state = getAssistantProviderSecretMigrationState();
|
||||
assert.strictEqual(state.attempts, attemptsBefore + 1);
|
||||
assert.strictEqual(state.lastFailureReason, "deps-unavailable");
|
||||
assert.ok(
|
||||
lines.some((line) =>
|
||||
line.includes("enc-v1 migration skipped: readEnvFile dependency is unavailable")
|
||||
),
|
||||
"the existing reader-missing warning text must stay verbatim"
|
||||
);
|
||||
assertNoSecrets(lines);
|
||||
});
|
||||
});
|
||||
|
||||
test("a failed batch write records env-write-failed and keeps the abort warning", async () => {
|
||||
await withMigrationEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => {
|
||||
const stored = legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET);
|
||||
const { env, deps } = createEnvDeps({
|
||||
DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: stored,
|
||||
});
|
||||
deps.writeEnvFileBatch = () => false; // simulated read-only .env
|
||||
let outcome;
|
||||
const { lines } = captureConsole(() => {
|
||||
outcome = migrateAssistantProviderSecretsV1ToV2(deps);
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 });
|
||||
assert.strictEqual(env.DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED, stored, ".env stays untouched");
|
||||
assert.strictEqual(getAssistantProviderSecretMigrationState().lastFailureReason, "env-write-failed");
|
||||
assert.ok(
|
||||
lines.some((line) => line.includes("enc-v1 migration aborted: .env update failed")),
|
||||
"the existing abort warning text must stay verbatim"
|
||||
);
|
||||
assertNoSecrets(lines);
|
||||
});
|
||||
});
|
||||
|
||||
test("a refused verified write records verified-write-refused", async () => {
|
||||
await withMigrationEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => {
|
||||
const stored = legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET);
|
||||
const { env, deps } = createEnvDeps({
|
||||
DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: stored,
|
||||
});
|
||||
// Simulated concurrent modification: the verified writer refuses.
|
||||
deps.writeEnvFileBatchVerified = () => false;
|
||||
let outcome;
|
||||
const { lines } = captureConsole(() => {
|
||||
outcome = migrateAssistantProviderSecretsV1ToV2(deps);
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(outcome, { retired: false, migrated: 0 });
|
||||
assert.strictEqual(env.DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED, stored);
|
||||
assert.strictEqual(
|
||||
getAssistantProviderSecretMigrationState().lastFailureReason,
|
||||
"verified-write-refused",
|
||||
"an explicit verified-writer refusal is distinguishable from a generic write failure"
|
||||
);
|
||||
assert.ok(
|
||||
lines.some((line) => line.includes("enc-v1 migration aborted: .env update failed")),
|
||||
"the refusal takes the same abort path and warning as any failed write"
|
||||
);
|
||||
assertNoSecrets(lines);
|
||||
});
|
||||
});
|
||||
|
||||
test("a partial run (one value re-wrapped, one lost) records undecryptable-value", async () => {
|
||||
await withMigrationEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => {
|
||||
const lostValue = legacyEncryptV1(GROQ_PLAINTEXT, "lost-secret");
|
||||
const { env, deps } = createEnvDeps({
|
||||
DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: lostValue,
|
||||
DASHBOARD_ASSISTANT_GOOGLE_AI_API_KEY_ENCRYPTED: legacyEncryptV1(GOOGLE_PLAINTEXT, DEDICATED_SECRET),
|
||||
});
|
||||
let outcome;
|
||||
const { lines } = captureConsole(() => {
|
||||
outcome = migrateAssistantProviderSecretsV1ToV2(deps);
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(outcome, { retired: false, migrated: 1 });
|
||||
assert.strictEqual(env.DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED, lostValue, "the lost value stays untouched");
|
||||
assert.strictEqual(
|
||||
decryptAssistantProviderToken(env.DASHBOARD_ASSISTANT_GOOGLE_AI_API_KEY_ENCRYPTED),
|
||||
GOOGLE_PLAINTEXT
|
||||
);
|
||||
assert.strictEqual(getAssistantProviderSecretMigrationState().lastFailureReason, "undecryptable-value");
|
||||
assert.strictEqual(getAssistantProviderSecretMigrationState().retired, false);
|
||||
assertNoSecrets(lines);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Retry scheduler. The tests below drive the scheduler through
|
||||
// createDashboardAssistantService; node:test mock timers stand in for the
|
||||
// backoff delays (no real-time waits), and every test leaves the module in a
|
||||
// known scheduling state for the next one. Order matters: the healing
|
||||
// retirement happens exactly once, in the second-to-last scheduler test.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("retries escalate through the backoff table and log one secret-free error per retry", async (t) => {
|
||||
t.mock.timers.enable({ apis: ["setTimeout"] });
|
||||
const mockedSetTimeout = global.setTimeout;
|
||||
const handles = [];
|
||||
// Spy only to capture handles: a pending mocked timer left behind by a test
|
||||
// poisons the NEXT mock-timers enable (its timers never fire), so every
|
||||
// mock-timer test must dequeue its leftovers via real clearTimeout below.
|
||||
global.setTimeout = (...args) => {
|
||||
const handle = mockedSetTimeout(...args);
|
||||
handles.push(handle);
|
||||
return handle;
|
||||
};
|
||||
try {
|
||||
await withMigrationEnv({}, async () => {
|
||||
const attemptsBefore = getAssistantProviderSecretMigrationState().attempts;
|
||||
const { state, deps } = createMutableEnvDeps();
|
||||
|
||||
let afterFirst = null;
|
||||
const { lines } = await captureConsoleAsync(async () => {
|
||||
createDashboardAssistantService(deps);
|
||||
await afterImmediate(); // first attempt: fails, schedules a 30s retry
|
||||
afterFirst = getAssistantProviderSecretMigrationState();
|
||||
|
||||
t.mock.timers.tick(30_000); // retry 1 → fails → 2min
|
||||
t.mock.timers.tick(120_000); // retry 2 → fails → 10min
|
||||
t.mock.timers.tick(600_000); // retry 3 → fails → 30min (cap)
|
||||
t.mock.timers.tick(1_800_000); // retry 4 → fails → 30min (cap repeats)
|
||||
});
|
||||
|
||||
// The FIRST attempt keeps today's logging behavior: the skip warning is
|
||||
// there, and no escalation error line exists for it (proven below by
|
||||
// exactly 4 error lines for 5 runs).
|
||||
assert.ok(lines.some((line) => line.includes("enc-v1 migration skipped: .env could not be read")));
|
||||
assert.strictEqual(afterFirst.retired, false);
|
||||
assert.strictEqual(afterFirst.lastFailureReason, "env-read-failed");
|
||||
assert.ok(afterFirst.nextRetryAtMs > afterFirst.lastAttemptAtMs, "a retry is scheduled");
|
||||
|
||||
assert.strictEqual(getAssistantProviderSecretMigrationState().attempts, attemptsBefore + 5, "first attempt + 4 retries");
|
||||
assert.strictEqual(getAssistantProviderSecretMigrationState().retired, false);
|
||||
|
||||
const errorLines = lines.filter((line) => line.includes("still unretired"));
|
||||
assert.strictEqual(errorLines.length, 4, "exactly one console.error per failed retry, never on the first attempt");
|
||||
const expectations = [
|
||||
/still unretired after 2 attempt\(s\) \(reason: env-read-failed\); retrying in 2 minutes\./,
|
||||
/still unretired after 3 attempt\(s\) \(reason: env-read-failed\); retrying in 10 minutes\./,
|
||||
/still unretired after 4 attempt\(s\) \(reason: env-read-failed\); retrying in 30 minutes\./,
|
||||
/still unretired after 5 attempt\(s\) \(reason: env-read-failed\); retrying in 30 minutes\./,
|
||||
];
|
||||
expectations.forEach((pattern, index) => {
|
||||
assert.match(errorLines[index], pattern, `retry ${index + 1} must report its attempt count, reason and next delay`);
|
||||
assert.ok(
|
||||
errorLines[index].includes("Provider keys in the legacy envelope remain protected only by the weak legacy chain"),
|
||||
"the escalation line must tell the operator what remains exposed"
|
||||
);
|
||||
});
|
||||
|
||||
// The scheduled retry time tracks the announced backoff (30min cap here).
|
||||
const finalState = getAssistantProviderSecretMigrationState();
|
||||
const delta = finalState.nextRetryAtMs - finalState.lastAttemptAtMs;
|
||||
assert.ok(delta >= 1_800_000 && delta < 1_800_000 + 5_000, "nextRetryAtMs = last attempt + announced delay");
|
||||
|
||||
assertNoSecrets(lines);
|
||||
assert.ok(state.writes.length === 0, "failing runs never write .env");
|
||||
});
|
||||
} finally {
|
||||
global.setTimeout = mockedSetTimeout;
|
||||
for (const handle of handles) clearTimeout(handle); // dequeue mock leftovers
|
||||
}
|
||||
});
|
||||
|
||||
test("repeated factory calls never stack retry timers", async (t) => {
|
||||
t.mock.timers.enable({ apis: ["setTimeout"] });
|
||||
const mockedSetTimeout = global.setTimeout;
|
||||
const scheduled = [];
|
||||
global.setTimeout = (...args) => {
|
||||
const handle = mockedSetTimeout(...args);
|
||||
const entry = { ms: args[1], unrefCalled: false, handle };
|
||||
const originalUnref = handle.unref.bind(handle);
|
||||
handle.unref = () => {
|
||||
entry.unrefCalled = true;
|
||||
return originalUnref();
|
||||
};
|
||||
scheduled.push(entry);
|
||||
return handle;
|
||||
};
|
||||
try {
|
||||
await withMigrationEnv({}, async () => {
|
||||
const attemptsBefore = getAssistantProviderSecretMigrationState().attempts;
|
||||
const { deps } = createMutableEnvDeps();
|
||||
|
||||
// Capture (and discard) console output: the tick-fired retry logs its
|
||||
// escalation error, which must not leak into the test runner output.
|
||||
await captureConsoleAsync(async () => {
|
||||
createDashboardAssistantService(deps);
|
||||
await afterImmediate(); // run 1 fails → schedules a retry
|
||||
createDashboardAssistantService(deps);
|
||||
await afterImmediate(); // run 2 fails → clears run 1's timer, schedules the next retry
|
||||
|
||||
assert.strictEqual(scheduled.length, 2, "each failed run schedules exactly one retry");
|
||||
// The escalation ladder may already be capped by earlier tests in this
|
||||
// process, so assert the table-relative property (never below the floor)
|
||||
// instead of absolute delays here — the full ladder is covered above.
|
||||
assert.ok(scheduled[0].ms >= 30_000, "the first retry uses a backoff table delay");
|
||||
assert.ok(scheduled[1].ms >= scheduled[0].ms, "the second failed run does not de-escalate");
|
||||
assert.ok(scheduled.every((entry) => entry.unrefCalled), "every scheduled retry handle is unref'd");
|
||||
|
||||
// Functional singleton proof: only run 2's timer is pending (run 1's
|
||||
// was cleared before re-scheduling). Tick up to exactly its deadline:
|
||||
// a stacked timer from run 1 (scheduled within the same mock-millisecond,
|
||||
// at the same delay) would fire during these ticks too.
|
||||
const pendingDelay = scheduled[1].ms;
|
||||
t.mock.timers.tick(pendingDelay - 1);
|
||||
assert.strictEqual(
|
||||
getAssistantProviderSecretMigrationState().attempts,
|
||||
attemptsBefore + 2,
|
||||
"no retry may fire before its scheduled delay"
|
||||
);
|
||||
t.mock.timers.tick(1);
|
||||
assert.strictEqual(
|
||||
getAssistantProviderSecretMigrationState().attempts,
|
||||
attemptsBefore + 3,
|
||||
"exactly ONE retry fired across both ticks (no stacked timers)"
|
||||
);
|
||||
assert.strictEqual(scheduled.length, 3, "the fired retry scheduled the next one");
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
global.setTimeout = mockedSetTimeout;
|
||||
for (const entry of scheduled) clearTimeout(entry.handle); // dequeue mock leftovers
|
||||
}
|
||||
});
|
||||
|
||||
test("the retry timer is unref'd so it never holds the worker open", async () => {
|
||||
// Real timers here: unref'd handles vanish from
|
||||
// process.getActiveResourcesInfo() (they no longer keep the loop alive),
|
||||
// which is the observable behavior the module must guarantee.
|
||||
const realSetTimeout = global.setTimeout;
|
||||
const realClearTimeout = global.clearTimeout;
|
||||
const scheduled = [];
|
||||
let clears = 0;
|
||||
global.setTimeout = (...args) => {
|
||||
const handle = realSetTimeout(...args);
|
||||
const entry = { ms: args[1], unrefCalled: false, handle };
|
||||
const originalUnref = handle.unref.bind(handle);
|
||||
handle.unref = () => {
|
||||
entry.unrefCalled = true;
|
||||
return originalUnref();
|
||||
};
|
||||
scheduled.push(entry);
|
||||
return handle;
|
||||
};
|
||||
global.clearTimeout = (...args) => {
|
||||
clears += 1;
|
||||
return realClearTimeout(...args);
|
||||
};
|
||||
const { lines } = await captureConsoleAsync(async () => {
|
||||
try {
|
||||
await withMigrationEnv({}, async () => {
|
||||
const { deps } = createMutableEnvDeps();
|
||||
|
||||
createDashboardAssistantService(deps);
|
||||
await afterImmediate();
|
||||
assert.strictEqual(scheduled.length, 1);
|
||||
assert.ok(scheduled[0].ms >= 30_000, "the retry uses a backoff table delay");
|
||||
assert.strictEqual(scheduled[0].unrefCalled, true, "unref() must be called on the retry handle");
|
||||
assert.strictEqual(scheduled[0].handle.hasRef(), false, "the handle must not hold the loop open");
|
||||
assert.ok(
|
||||
!process.getActiveResourcesInfo().includes("Timeout"),
|
||||
"an unref'd retry must not appear as an active event-loop resource"
|
||||
);
|
||||
|
||||
// A second construction re-points the scheduler and must clear the
|
||||
// previous handle before scheduling a new one (singleton rule). The
|
||||
// delta matters: the run before this one already consumed the stale
|
||||
// pending handle left by the previous test with one clear.
|
||||
const clearsAfterFirstRun = clears;
|
||||
createDashboardAssistantService(deps);
|
||||
await afterImmediate();
|
||||
assert.strictEqual(scheduled.length, 2);
|
||||
assert.ok(scheduled[1].ms >= scheduled[0].ms, "the backoff does not de-escalate");
|
||||
assert.strictEqual(clears, clearsAfterFirstRun + 1, "the previous retry timer must be cleared before re-scheduling");
|
||||
assert.strictEqual(scheduled[1].unrefCalled, true);
|
||||
assert.ok(!process.getActiveResourcesInfo().includes("Timeout"));
|
||||
|
||||
// Deliberately leave the single pending (unref'd) retry timer: the
|
||||
// next test's first scheduler run clears it. Even if the suite somehow
|
||||
// outlived the delay, the timer is unref'd and must not block exit.
|
||||
});
|
||||
} finally {
|
||||
global.setTimeout = realSetTimeout;
|
||||
global.clearTimeout = realClearTimeout;
|
||||
}
|
||||
});
|
||||
assertNoSecrets(lines);
|
||||
});
|
||||
|
||||
test("a scheduled retry re-runs the migration and heals retirement in-process", async (t) => {
|
||||
t.mock.timers.enable({ apis: ["setTimeout"] });
|
||||
const mockedSetTimeout = global.setTimeout;
|
||||
const scheduled = [];
|
||||
global.setTimeout = (...args) => {
|
||||
const handle = mockedSetTimeout(...args);
|
||||
scheduled.push({ ms: args[1], handle });
|
||||
return handle;
|
||||
};
|
||||
try {
|
||||
await withMigrationEnv({ DASHBOARD_ASSISTANT_ENCRYPTION_SECRET: DEDICATED_SECRET }, async () => {
|
||||
const attemptsBefore = getAssistantProviderSecretMigrationState().attempts;
|
||||
const { state, deps } = createMutableEnvDeps();
|
||||
|
||||
let healed;
|
||||
// One capture over the whole window: the first construction's failing
|
||||
// run logs its skip warning too, which must not leak into the runner
|
||||
// output any more than the retry's logs do.
|
||||
const { lines } = await captureConsoleAsync(async () => {
|
||||
createDashboardAssistantService(deps);
|
||||
await afterImmediate(); // fails: .env unreadable → retry at +30s
|
||||
assert.strictEqual(getAssistantProviderSecretMigrationState().retired, false);
|
||||
assert.ok(getAssistantProviderSecretMigrationState().nextRetryAtMs > 0);
|
||||
|
||||
// The blocking condition goes away; the pending retry must pick it up
|
||||
// WITHOUT a restart — that is the whole point of the scheduler.
|
||||
state.failReads = false;
|
||||
state.env = {
|
||||
DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED: legacyEncryptV1(GROQ_PLAINTEXT, DEDICATED_SECRET),
|
||||
};
|
||||
|
||||
const retryDelayMs = scheduled[0].ms; // whatever the backoff table currently says
|
||||
t.mock.timers.tick(retryDelayMs); // the retry fires and succeeds
|
||||
healed = getAssistantProviderSecretMigrationState();
|
||||
});
|
||||
|
||||
assert.strictEqual(healed.retired, true, "the retry must flip retirement once deps succeed");
|
||||
assert.strictEqual(healed.nextRetryAtMs, 0, "a retired process schedules nothing further");
|
||||
assert.strictEqual(healed.lastFailureReason, "", "full success clears the failure history");
|
||||
assert.strictEqual(healed.attempts, attemptsBefore + 2);
|
||||
assert.strictEqual(state.writes.length, 1, "the retry performed the .env batch write");
|
||||
assert.strictEqual(
|
||||
scheduled.length,
|
||||
1,
|
||||
"a successful run must not schedule any further retry"
|
||||
);
|
||||
assert.ok(
|
||||
lines.some((line) => line.includes("re-encrypted 1 provider API key(s) as enc-v2 under DASHBOARD_ASSISTANT_ENCRYPTION_SECRET")),
|
||||
"the success outcome is logged"
|
||||
);
|
||||
assert.ok(
|
||||
!lines.some((line) => line.includes("still unretired")),
|
||||
"a retry that SUCCEEDS must not log the escalation error"
|
||||
);
|
||||
assertNoSecrets(lines);
|
||||
|
||||
// A further trigger on the retired process schedules nothing more.
|
||||
createDashboardAssistantService(deps);
|
||||
await afterImmediate();
|
||||
assert.strictEqual(scheduled.length, 1, "post-retirement triggers stay scheduling-free");
|
||||
assert.strictEqual(getAssistantProviderSecretMigrationState().nextRetryAtMs, 0);
|
||||
// A long tick that would fire ANY stray retry timer: none may exist.
|
||||
t.mock.timers.tick(10 * 1_800_000);
|
||||
assert.strictEqual(
|
||||
getAssistantProviderSecretMigrationState().attempts,
|
||||
attemptsBefore + 3,
|
||||
"the re-confirmation run happened, but no retry timer existed to fire"
|
||||
);
|
||||
});
|
||||
} finally {
|
||||
global.setTimeout = mockedSetTimeout;
|
||||
}
|
||||
});
|
||||
|
||||
test("a retirement-confirmed process performs no retries even when runs keep failing", async () => {
|
||||
const realSetTimeout = global.setTimeout;
|
||||
let scheduledCalls = 0;
|
||||
global.setTimeout = (...args) => {
|
||||
scheduledCalls += 1;
|
||||
return realSetTimeout(...args);
|
||||
};
|
||||
const { lines } = await captureConsoleAsync(async () => {
|
||||
try {
|
||||
await withMigrationEnv({}, async () => {
|
||||
const attemptsBefore = getAssistantProviderSecretMigrationState().attempts;
|
||||
const { deps } = createMutableEnvDeps();
|
||||
|
||||
createDashboardAssistantService(deps);
|
||||
await afterImmediate();
|
||||
|
||||
const state = getAssistantProviderSecretMigrationState();
|
||||
assert.strictEqual(state.retired, true, "retirement is one-way per process");
|
||||
assert.strictEqual(state.attempts, attemptsBefore + 1, "the run itself still happened");
|
||||
assert.strictEqual(state.lastFailureReason, "env-read-failed", "the run's own failure stays recorded");
|
||||
assert.strictEqual(state.nextRetryAtMs, 0, "but a retired process schedules no retry");
|
||||
assert.strictEqual(scheduledCalls, 0, "setTimeout must never be called once retired");
|
||||
assert.ok(!process.getActiveResourcesInfo().includes("Timeout"));
|
||||
});
|
||||
} finally {
|
||||
global.setTimeout = realSetTimeout;
|
||||
}
|
||||
});
|
||||
assertNoSecrets(lines);
|
||||
});
|
||||
Reference in new issue
Block a user